vue实现平缓弹幕
Vue 实现平滑弹幕的方法
在 Vue 中实现平滑弹幕效果,可以通过 CSS 动画和 Vue 的动态渲染结合完成。以下是具体实现方式:
弹幕数据结构设计
使用数组存储弹幕信息,每条弹幕包含内容、颜色、位置等属性:
data() {
return {
danmus: [],
colors: ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff']
}
}
弹幕容器样式
设置弹幕容器为相对定位,溢出隐藏:
.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
background: #000;
}
弹幕项组件
创建弹幕项组件,使用 CSS 过渡实现平滑移动:
<template>
<div
class="danmu-item"
:style="{
color: item.color,
top: item.top + 'px',
transform: `translateX(${item.left}px)`,
transition: `transform ${item.duration}s linear`
}"
>
{{ item.text }}
</div>
</template>
<style>
.danmu-item {
position: absolute;
white-space: nowrap;
font-size: 20px;
text-shadow: 1px 1px 2px #000;
}
</style>
弹幕发射逻辑
通过定时器生成新弹幕并设置动画:
methods: {
launchDanmu() {
const height = this.$refs.container.clientHeight
const width = this.$refs.container.clientWidth
const newDanmu = {
text: '这是一条弹幕',
color: this.colors[Math.floor(Math.random() * this.colors.length)],
top: Math.random() * (height - 30),
left: width,
duration: 5 + Math.random() * 5
}
this.danmus.push(newDanmu)
setTimeout(() => {
this.$nextTick(() => {
newDanmu.left = -this.$refs.container.clientWidth
})
}, 100)
setTimeout(() => {
this.danmus.shift()
}, newDanmu.duration * 1000)
}
}
性能优化建议
使用 requestAnimationFrame 优化动画性能,避免频繁的 DOM 操作:

animate() {
this.danmus.forEach(danmu => {
danmu.left -= 2
if (danmu.left < -100) {
danmu.left = this.$refs.container.clientWidth
}
})
requestAnimationFrame(this.animate)
}
注意事项
弹幕数量过多时需要考虑虚拟滚动技术,移除屏幕外的弹幕元素以提升性能。可以结合 Web Worker 处理大量弹幕数据的计算,避免阻塞主线程。






