Vue实现弹幕漂浮效果
Vue实现弹幕漂浮效果的方法
使用CSS动画实现基础漂浮
通过CSS的@keyframes定义横向移动动画,结合Vue的v-for动态渲染弹幕元素。弹幕元素需设置position: absolute及随机生成垂直位置。
<template>
<div class="danmu-container">
<div
v-for="(item, index) in danmuList"
:key="index"
class="danmu-item"
:style="{ top: item.top + 'px', animationDuration: item.duration + 's' }"
>
{{ item.text }}
</div>
</div>
</template>
<style>
.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
}
.danmu-item {
position: absolute;
white-space: nowrap;
animation: move linear;
}
@keyframes move {
from { transform: translateX(100%); }
to { transform: translateX(-100%); }
}
</style>
动态数据绑定与随机参数
在Vue的data或setup中定义弹幕数组,通过方法随机生成垂直位置和动画时长。使用setInterval持续添加新弹幕。

export default {
data() {
return {
danmuList: [],
colors: ['#ff0000', '#00ff00', '#0000ff']
}
},
methods: {
addDanmu(text) {
this.danmuList.push({
text,
top: Math.random() * 250,
duration: 5 + Math.random() * 5,
color: this.colors[Math.floor(Math.random() * this.colors.length)]
})
}
},
mounted() {
setInterval(() => {
this.addDanmu('新弹幕' + Date.now())
}, 1000)
}
}
优化性能与事件处理
弹幕移出屏幕后应从DOM中移除,避免内存泄漏。通过监听animationend事件实现。

<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'
}"
@animationend="removeDanmu(index)"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
methods: {
removeDanmu(index) {
this.danmuList.splice(index, 1)
}
}
}
</script>
使用第三方库增强功能
对于复杂需求可考虑使用专门库如vue-danmaku。安装后通过预设配置快速实现高级功能如暂停、速度控制等。
npm install vue-danmaku
import VueDanmaku from 'vue-danmaku'
export default {
components: { VueDanmaku },
template: `
<vue-danmaku
:danmus="danmuList"
:speed="100"
:randomChannel="true"
/>
`
}
注意事项
- 弹幕数量需控制,过多会影响性能
- 移动端需考虑触摸事件冲突
- 内容安全过滤防止XSS攻击
- 使用
requestAnimationFrame替代setInterval可获得更平滑的动画效果






