vue实现发送弹幕
Vue实现发送弹幕功能
核心思路
通过Vue的数据绑定和列表渲染能力,结合CSS动画实现弹幕从右向左移动的效果。弹幕数据存储在数组中,动态添加新弹幕并控制其样式和位置。
实现步骤
1. 创建Vue实例与数据结构
new Vue({
el: '#app',
data: {
danmuList: [], // 存储弹幕对象
inputText: '' // 输入框内容
}
})
2. 弹幕发送方法
methods: {
sendDanmu() {
if (!this.inputText.trim()) return
const newDanmu = {
id: Date.now(),
text: this.inputText,
top: Math.random() * 80 + '%', // 随机垂直位置
color: `rgb(${
Math.floor(Math.random() * 256)
}, ${
Math.floor(Math.random() * 256)
}, ${
Math.floor(Math.random() * 256)
})` // 随机颜色
}
this.danmuList.push(newDanmu)
this.inputText = ''
}
}
3. 弹幕容器与样式
<div class="danmu-container">
<div
v-for="item in danmuList"
:key="item.id"
class="danmu-item"
:style="{
color: item.color,
top: item.top
}"
>
{{ item.text }}
</div>
</div>
.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
background: #000;
}
.danmu-item {
position: absolute;
white-space: nowrap;
animation: move linear 10s;
}
@keyframes move {
from { transform: translateX(100%); }
to { transform: translateX(-100%); }
}
4. 输入框与发送按钮
<div class="input-area">
<input v-model="inputText" @keyup.enter="sendDanmu">
<button @click="sendDanmu">发送</button>
</div>
高级优化方向
性能优化
- 使用虚拟滚动技术处理大量弹幕
- 对离开屏幕的弹幕进行回收利用
- 添加弹幕防撞检测算法
功能扩展
- 实现弹幕暂停/继续功能
- 添加弹幕速度控制选项
- 支持图片/表情弹幕
- 添加弹幕屏蔽过滤功能
完整示例代码
new Vue({
el: '#app',
data: {
danmuList: [],
inputText: ''
},
methods: {
sendDanmu() {
if (!this.inputText.trim()) return
this.danmuList.push({
id: Date.now(),
text: this.inputText,
top: Math.random() * 80 + '%',
color: `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`
})
this.inputText = ''
}
}
})
<div id="app">
<div class="danmu-container">
<div
v-for="item in danmuList"
:key="item.id"
class="danmu-item"
:style="{ color: item.color, top: item.top }"
>
{{ item.text }}
</div>
</div>
<div class="input-area">
<input v-model="inputText" @keyup.enter="sendDanmu">
<button @click="sendDanmu">发送</button>
</div>
</div>






