vue+实现弹幕
实现弹幕的基本思路
弹幕功能通常包括文字在屏幕上滚动显示、动态生成弹幕内容、控制弹幕速度和密度等。Vue 的实现可以结合 CSS 动画和动态组件。
弹幕数据管理
使用 Vue 的 data 或 ref(Composition API)存储弹幕列表。每条弹幕包含文本内容、颜色、位置等信息。
data() {
return {
danmus: [],
colors: ['#ff0000', '#00ff00', '#0000ff', '#ffff00'],
}
}
弹幕生成与添加
通过方法动态生成弹幕并添加到列表中。可以设置随机颜色、垂直位置等属性。
methods: {
addDanmu(text) {
const top = Math.floor(Math.random() * 80) + 10;
const color = this.colors[Math.floor(Math.random() * this.colors.length)];
this.danmus.push({
text,
color,
top: `${top}%`,
id: Date.now(),
});
}
}
弹幕渲染与动画
使用 v-for 渲染弹幕列表,并通过 CSS 实现滚动动画。弹幕组件需要绝对定位,并设置 left 从 100% 到 -100% 的动画。

<template>
<div class="danmu-container">
<div
v-for="danmu in danmus"
:key="danmu.id"
class="danmu-item"
:style="{ color: danmu.color, top: danmu.top }"
>
{{ danmu.text }}
</div>
</div>
</template>
<style>
.danmu-container {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.danmu-item {
position: absolute;
white-space: nowrap;
animation: move linear;
animation-duration: 10s;
}
@keyframes move {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
</style>
弹幕生命周期管理
弹幕移出屏幕后需要从列表中移除,避免内存泄漏。通过 animationend 事件监听动画结束。
mounted() {
document.querySelectorAll('.danmu-item').forEach(item => {
item.addEventListener('animationend', () => {
this.danmus = this.danmus.filter(d => d.id !== parseInt(item.dataset.id));
});
});
}
弹幕发送功能
添加输入框和发送按钮,调用 addDanmu 方法发送新弹幕。

<div class="danmu-input">
<input v-model="inputText" @keyup.enter="sendDanmu" />
<button @click="sendDanmu">发送</button>
</div>
<script>
methods: {
sendDanmu() {
if (this.inputText.trim()) {
this.addDanmu(this.inputText);
this.inputText = '';
}
}
}
</script>
弹幕速度与密度控制
通过调整动画时间和生成频率控制弹幕速度和密度。可以使用 setInterval 定时生成弹幕。
created() {
setInterval(() => {
this.addDanmu('随机弹幕' + Math.floor(Math.random() * 100));
}, 1000);
}
弹幕重叠避免
通过计算弹幕位置避免重叠。可以使用更复杂的算法动态调整新弹幕的垂直位置。
methods: {
findAvailableTop() {
const occupied = this.danmus.map(d => parseInt(d.top));
for (let i = 10; i <= 90; i += 10) {
if (!occupied.includes(i)) return `${i}%`;
}
return `${Math.floor(Math.random() * 80) + 10}%`;
}
}
弹幕暂停与继续
通过动态修改 CSS 动画的 play-state 控制弹幕暂停。
data() {
return {
isPaused: false,
}
},
methods: {
togglePause() {
this.isPaused = !this.isPaused;
const items = document.querySelectorAll('.danmu-item');
items.forEach(item => {
item.style.animationPlayState = this.isPaused ? 'paused' : 'running';
});
}
}






