vue 实现弹幕js
Vue 实现弹幕功能
在Vue中实现弹幕功能,可以通过动态渲染DOM元素并结合CSS动画或JavaScript定时器控制移动效果。以下是两种常见实现方式:
基于CSS动画的实现
模板部分
<template>
<div class="danmu-container">
<div
v-for="(item, index) in danmuList"
:key="index"
class="danmu-item"
:style="{
top: `${item.top}px`,
animationDuration: `${item.speed}s`
}"
>
{{ item.text }}
</div>
</div>
</template>
样式部分

.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%); }
}
逻辑部分
export default {
data() {
return {
danmuList: [],
colors: ['#ff0000', '#00ff00', '#0000ff', '#ffff00']
}
},
methods: {
addDanmu(text) {
const speed = 5 + Math.random() * 5;
const top = Math.random() * 250;
const color = this.colors[Math.floor(Math.random() * this.colors.length)];
this.danmuList.push({
text,
speed,
top,
color
});
setTimeout(() => {
this.danmuList.shift();
}, speed * 1000);
}
}
}
基于JavaScript定时器的实现
模板部分

<template>
<div class="danmu-container" ref="container">
<div
v-for="(item, index) in danmuList"
:key="index"
class="danmu-item"
:style="{
top: `${item.top}px`,
left: `${item.left}px`,
color: item.color
}"
>
{{ item.text }}
</div>
</div>
</template>
逻辑部分
export default {
data() {
return {
danmuList: [],
timer: null
}
},
mounted() {
this.timer = setInterval(this.updateDanmuPosition, 16);
},
beforeDestroy() {
clearInterval(this.timer);
},
methods: {
addDanmu(text) {
const containerWidth = this.$refs.container.offsetWidth;
const item = {
text,
left: containerWidth,
top: Math.random() * 250,
color: `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`,
speed: 2 + Math.random() * 3
};
this.danmuList.push(item);
},
updateDanmuPosition() {
this.danmuList.forEach(item => {
item.left -= item.speed;
});
this.danmuList = this.danmuList.filter(item => item.left > -100);
}
}
}
性能优化建议
- 使用虚拟滚动技术处理大量弹幕时,只渲染可视区域内的弹幕元素
- 对于频繁变动的数据,使用
Object.freeze()冻结不需要响应式的数据 - 采用Web Workers处理弹幕位置计算等密集型任务
- 使用
requestAnimationFrame代替setInterval实现更流畅的动画
扩展功能实现
实现弹幕碰撞检测
checkCollision(newItem) {
return this.danmuList.some(item => {
return Math.abs(item.top - newItem.top) < 20 &&
Math.abs(item.left - newItem.left) < 100;
});
}
实现弹幕暂停/继续
pauseDanmu() {
cancelAnimationFrame(this.animationId);
},
resumeDanmu() {
this.updateDanmuPosition();
}
以上实现方式可根据实际需求选择或组合使用。CSS动画实现更简洁,JavaScript控制更灵活。建议在移动端优先考虑CSS动画方案以获得更好的性能表现。






