vue实现弹幕
Vue 实现弹幕功能
弹幕功能通常包括文字在屏幕上滚动显示的效果。以下是使用 Vue 实现弹幕的几种方法:
使用 CSS 动画实现基础弹幕
创建一个 Vue 组件,利用 CSS 的 @keyframes 实现弹幕的滚动效果。

<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>
<script>
export default {
data() {
return {
danmuList: [],
containerHeight: 300 // 容器高度
};
},
methods: {
addDanmu(text) {
const top = Math.random() * this.containerHeight;
const duration = 5 + Math.random() * 5; // 随机持续时间
this.danmuList.push({ text, top, duration });
// 弹幕播放完成后移除
setTimeout(() => {
this.danmuList.shift();
}, duration * 1000);
}
}
};
</script>
<style>
.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
background: #000;
}
.danmu-item {
position: absolute;
white-space: nowrap;
color: #fff;
animation: danmuMove linear;
}
@keyframes danmuMove {
from { transform: translateX(100%); }
to { transform: translateX(-100%); }
}
</style>
使用 Vue 过渡动画
通过 Vue 的 <transition-group> 实现弹幕的进入和离开动画。
<template>
<div class="danmu-container">
<transition-group name="danmu">
<div
v-for="(item, index) in danmuList"
:key="index"
class="danmu-item"
:style="{ top: `${item.top}px` }"
>
{{ item.text }}
</div>
</transition-group>
</div>
</template>
<script>
export default {
data() {
return {
danmuList: [],
containerHeight: 300
};
},
methods: {
addDanmu(text) {
const top = Math.random() * this.containerHeight;
this.danmuList.push({ text, top });
setTimeout(() => {
this.danmuList.shift();
}, 5000);
}
}
};
</script>
<style>
.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
background: #000;
}
.danmu-item {
position: absolute;
white-space: nowrap;
color: #fff;
animation: danmuMove 5s linear;
}
@keyframes danmuMove {
from { transform: translateX(100%); }
to { transform: translateX(-100%); }
}
.danmu-enter-active, .danmu-leave-active {
transition: all 0.5s;
}
.danmu-enter, .danmu-leave-to {
opacity: 0;
}
</style>
使用第三方库
如果需要更复杂的功能(如弹幕碰撞检测、颜色自定义等),可以使用第三方库如 rc-bullets。

安装:
npm install rc-bullets
使用:
<template>
<div ref="danmuContainer" style="width: 100%; height: 300px;"></div>
</template>
<script>
import { Bullet } from 'rc-bullets';
export default {
mounted() {
const screen = new Bullet(this.$refs.danmuContainer, {
trackHeight: 30,
onStart: () => {
screen.push('这是一条弹幕');
}
});
}
};
</script>
弹幕功能优化
- 性能优化:避免频繁操作 DOM,可以使用虚拟列表技术。
- 弹幕防撞:计算弹幕的宽度和速度,避免重叠。
- 自定义样式:支持颜色、字体大小等自定义。
- 暂停和继续:通过控制 CSS 动画的
animation-play-state实现。
以上方法可以根据实际需求选择或组合使用。






