Vue实现弹幕漂浮效果
Vue实现弹幕弹幕漂浮效果
核心思路
通过动态生成弹幕DOM元素,利用CSS动画或JavaScript控制其从右向左移动,并通过Vue的数据驱动特性管理弹幕生命周期。
基础实现步骤
创建弹幕组件
定义单条弹幕的模板和样式,包含文字内容、颜色、速度等属性。

<template>
<div class="danmu-item" :style="style">
{{ text }}
</div>
</template>
<script>
export default {
props: ['text', 'color', 'speed'],
computed: {
style() {
return {
color: this.color,
animationDuration: `${this.speed}s`
};
}
}
};
</script>
<style>
.danmu-item {
position: absolute;
white-space: nowrap;
animation: move linear;
}
@keyframes move {
from { transform: translateX(100vw); }
to { transform: translateX(-100%); }
}
</style>
管理弹幕队列
在父组件中使用数组存储弹幕数据,通过定时器动态添加新弹幕并清理过期弹幕。
<template>
<div class="danmu-container">
<DanmuItem
v-for="(item, index) in danmuList"
:key="index"
:text="item.text"
:color="item.color"
:speed="item.speed"
/>
</div>
</template>
<script>
export default {
data() {
return {
danmuList: [],
colors: ['#ff0000', '#00ff00', '#0000ff']
};
},
methods: {
addDanmu(text) {
this.danmuList.push({
text,
color: this.colors[Math.floor(Math.random() * 3)],
speed: 5 + Math.random() * 5
});
}
}
};
</script>
进阶优化方案
性能优化
使用requestAnimationFrame替代CSS动画,手动控制弹幕位置以减少重绘开销。

updatePosition() {
this.danmuList.forEach(item => {
item.x -= 2;
if (item.x < -item.width) this.removeDanmu(item);
});
requestAnimationFrame(this.updatePosition);
}
碰撞检测
通过计算弹幕的Y轴位置和高度,避免重叠显示。
getRandomY() {
const y = Math.random() * (containerHeight - danmuHeight);
return this.isOverlap(y) ? this.getRandomY() : y;
}
互动功能
添加点击事件暂停或加速特定弹幕。
<div @click="handleClick(item)">{{ item.text }}</div>
handleClick(item) {
item.speed = item.speed > 1 ? 0 : 5;
}
完整示例代码
查看CodePen示例(模拟链接)
包含:随机颜色、速度控制、自动清理、响应式布局等功能实现。





