vue.js 实现弹幕
Vue.js 实现弹幕功能
弹幕功能通常涉及动态生成、移动和销毁大量文本元素。以下是基于 Vue.js 的实现方法:
核心思路
- 使用 CSS 动画控制弹幕的横向移动
- 通过 Vue 的
v-for动态渲染弹幕列表 - 使用定时器控制弹幕的生成和销毁
实现步骤
HTML 结构
<template>
<div class="danmu-container">
<div
v-for="(item, index) in danmuList"
:key="index"
class="danmu-item"
:style="{
top: item.top + 'px',
color: item.color,
animationDuration: item.duration + 's'
}"
>
{{ item.text }}
</div>
<input v-model="inputText" @keyup.enter="sendDanmu" />
</div>
</template>
CSS 样式
.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
background: #000;
}
.danmu-item {
position: absolute;
white-space: nowrap;
font-size: 20px;
animation: danmuMove linear;
}
@keyframes danmuMove {
from { transform: translateX(100%); }
to { transform: translateX(-100%); }
}
JavaScript 逻辑
export default {
data() {
return {
danmuList: [],
inputText: '',
colors: ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff']
}
},
methods: {
sendDanmu() {
if (!this.inputText.trim()) return
const newDanmu = {
text: this.inputText,
top: Math.random() * 250,
color: this.colors[Math.floor(Math.random() * this.colors.length)],
duration: 5 + Math.random() * 5
}
this.danmuList.push(newDanmu)
this.inputText = ''
setTimeout(() => {
this.danmuList.shift()
}, newDanmu.duration * 1000)
},
autoGenerate() {
setInterval(() => {
const texts = ['666', '哈哈哈', '太棒了', '学到了', 'Vue牛逼']
const randomText = texts[Math.floor(Math.random() * texts.length)]
this.danmuList.push({
text: randomText,
top: Math.random() * 250,
color: this.colors[Math.floor(Math.random() * this.colors.length)],
duration: 5 + Math.random() * 5
})
}, 1000)
}
},
mounted() {
this.autoGenerate()
}
}
优化方向
性能优化
- 使用虚拟滚动技术处理大量弹幕
- 对弹幕元素进行对象池管理
- 使用 CSS
will-change属性提升动画性能
功能扩展
- 添加弹幕屏蔽功能
- 实现弹幕碰撞检测
- 支持不同弹幕轨道
- 添加弹幕透明度渐变效果
实际应用建议
- 对于直播场景,需要结合 WebSocket 实现实时弹幕
- 对于视频网站,需要根据播放时间同步弹幕
- 考虑添加弹幕过滤系统,防止不当内容
以上实现提供了基础弹幕功能,可以根据实际需求进行扩展和优化。







