vue实现弹幕移动效果
Vue 实现弹幕移动效果
弹幕移动效果可以通过 CSS 动画结合 Vue 的动态渲染实现。以下是具体实现方法:
基本实现思路
-
数据驱动弹幕内容
使用 Vue 的v-for动态渲染弹幕列表,每条弹幕包含文本内容和初始位置信息。 -
CSS 动画控制移动
通过 CSStransform和animation实现弹幕从右向左的平滑移动。 -
随机生成弹幕位置
弹幕的垂直位置(top 值)随机生成,避免重叠。
代码实现
1. 模板部分
<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>
<button @click="addDanmu">添加弹幕</button>
</div>
</template>
2. 脚本部分
<script>
export default {
data() {
return {
danmuList: [],
colors: ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff'],
texts: ['Hello!', 'Vue 弹幕', '测试弹幕', '666', 'Awesome']
}
},
methods: {
addDanmu() {
const newDanmu = {
text: this.texts[Math.floor(Math.random() * this.texts.length)],
top: Math.floor(Math.random() * 300), // 随机垂直位置
color: this.colors[Math.floor(Math.random() * this.colors.length)],
duration: 5 + Math.random() * 5 // 随机动画时长
};
this.danmuList.push(newDanmu);
// 动画结束后移除弹幕
setTimeout(() => {
this.danmuList.shift();
}, newDanmu.duration * 1000);
}
},
mounted() {
// 初始加载几条弹幕
for (let i = 0; i < 5; i++) {
this.addDanmu();
}
}
}
</script>
3. 样式部分
<style scoped>
.danmu-container {
position: relative;
width: 100%;
height: 400px;
border: 1px solid #ccc;
overflow: hidden;
}
.danmu-item {
position: absolute;
white-space: nowrap;
font-size: 20px;
animation: danmuMove linear;
animation-fill-mode: forwards;
right: 0;
}
@keyframes danmuMove {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
</style>
功能扩展
-
弹幕速度控制
通过调整animationDuration的值可以改变弹幕移动速度,值越小速度越快。
-
弹幕碰撞检测
如果需要避免弹幕重叠,可以记录每条弹幕的top和height,新增弹幕时检测是否与现有弹幕重叠。 -
用户输入弹幕
添加输入框,允许用户输入自定义弹幕内容:<input v-model="inputText" placeholder="输入弹幕内容" /> <button @click="sendDanmu">发送</button>对应方法:

sendDanmu() { if (!this.inputText.trim()) return; this.addDanmu(this.inputText); this.inputText = ''; } -
弹幕透明度渐变
在 CSS 动画中添加透明度变化:@keyframes danmuMove { 0% { transform: translateX(100%); opacity: 0; } 10% { opacity: 1; } 90% { opacity: 1; } 100% { transform: translateX(-100%); opacity: 0; } }
性能优化
-
虚拟滚动
对于大量弹幕,可以使用虚拟滚动技术,只渲染可视区域内的弹幕。 -
对象池复用
弹幕对象可以复用,避免频繁创建和销毁 DOM 节点。 -
使用 requestAnimationFrame
对于更复杂的弹幕运动轨迹,可以用requestAnimationFrame替代 CSS 动画。
通过以上方法,可以轻松实现 Vue 中的弹幕移动效果,并根据需求扩展更多功能。






