vue实现抖音弹幕
Vue 实现抖音弹幕效果
抖音弹幕的核心特点是随机位置、颜色、速度和动画效果。以下是基于 Vue 的实现方法:
弹幕数据与样式
弹幕数据通常存储在数组中,每条弹幕包含文本、颜色、位置等信息。
data() {
return {
danmus: [
{ text: '哈哈哈', color: '#ff0000', top: '10%', speed: 5 },
{ text: '666', color: '#00ff00', top: '30%', speed: 8 }
],
newDanmu: ''
}
}
弹幕组件结构
使用 Vue 的模板语法创建弹幕容器和单个弹幕元素。

<div class="danmu-container">
<div
v-for="(danmu, index) in danmus"
:key="index"
class="danmu-item"
:style="{
color: danmu.color,
top: danmu.top,
animationDuration: `${danmu.speed}s`
}"
>
{{ danmu.text }}
</div>
</div>
<input v-model="newDanmu" @keyup.enter="addDanmu">
CSS 动画效果
通过 CSS 动画实现弹幕从右向左移动的效果。
.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
}
.danmu-item {
position: absolute;
white-space: nowrap;
animation: danmuMove linear;
right: 0;
}
@keyframes danmuMove {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
添加新弹幕
在方法中添加新弹幕,随机生成颜色和位置。

methods: {
addDanmu() {
if (!this.newDanmu.trim()) return;
const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff'];
const tops = ['10%', '20%', '30%', '40%', '50%', '60%', '70%', '80%'];
const speeds = [5, 6, 7, 8, 9, 10];
this.danmus.push({
text: this.newDanmu,
color: colors[Math.floor(Math.random() * colors.length)],
top: tops[Math.floor(Math.random() * tops.length)],
speed: speeds[Math.floor(Math.random() * speeds.length)]
});
this.newDanmu = '';
}
}
自动清理弹幕
使用生命周期钩子或计时器清理已经完成动画的弹幕。
mounted() {
setInterval(() => {
this.danmus = this.danmus.filter(danmu => {
const element = document.querySelector(`.danmu-item:contains('${danmu.text}')`);
return element && getComputedStyle(element).opacity !== '0';
});
}, 1000);
}
优化性能
对于大量弹幕,可以使用虚拟滚动或动态渲染优化性能。
computed: {
visibleDanmus() {
return this.danmus.slice(0, 50); // 只显示前50条
}
}
完整示例
将上述代码整合到 Vue 单文件组件中即可实现基础抖音弹幕效果。可根据需求添加更多功能如弹幕碰撞检测、用户屏蔽等。






