vue实现平缓弹幕
实现平缓弹幕的基本思路
平缓弹幕的核心在于控制弹幕的运动速度和轨迹,使其看起来流畅自然。通常需要结合CSS动画或JavaScript动态计算位置。
CSS动画实现方法
使用CSS的@keyframes和transform属性实现水平移动的弹幕效果。通过调整动画时长和延迟,可以控制弹幕的速度和出现时间。
<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`,
animationDelay: `${item.delay}s`
}"
>
{{ item.text }}
</div>
</div>
</template>
<style>
.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
}
.danmu-item {
position: absolute;
white-space: nowrap;
animation: danmuMove linear;
}
@keyframes danmuMove {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
</style>
JavaScript动态计算实现
通过requestAnimationFrame实现更精细的控制,可以动态计算每个弹幕的位置,实现变速或曲线运动效果。
data() {
return {
danmuList: [],
containerWidth: 0
}
},
mounted() {
this.containerWidth = this.$el.offsetWidth;
this.startDanmu();
},
methods: {
addDanmu(text) {
this.danmuList.push({
text,
x: this.containerWidth,
y: Math.random() * 250,
speed: 2 + Math.random() * 3
});
},
startDanmu() {
const animate = () => {
this.danmuList.forEach(item => {
item.x -= item.speed;
if (item.x < -100) {
item.x = this.containerWidth;
}
});
requestAnimationFrame(animate);
};
animate();
}
}
优化弹幕性能
对于大量弹幕,使用虚拟滚动技术只渲染可视区域内的弹幕,避免不必要的DOM操作和重绘。
computed: {
visibleDanmus() {
return this.danmuList.filter(item =>
item.x > -100 && item.x < this.containerWidth
);
}
}
弹幕碰撞检测
实现弹幕不重叠的算法,需要计算每条弹幕的宽度和位置,动态调整新弹幕的垂直位置。
methods: {
findAvailableY(text) {
const textWidth = this.getTextWidth(text);
let y = 0;
let found = false;
while (!found && y < 250) {
const collision = this.danmuList.some(item =>
item.y >= y && item.y <= y + 20 &&
item.x + textWidth > 0 && item.x < this.containerWidth
);
if (!collision) {
found = true;
} else {
y += 25;
}
}
return found ? y : Math.random() * 250;
},
getTextWidth(text) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.font = '16px Arial';
return ctx.measureText(text).width;
}
}
弹幕样式多样化
通过动态类名或样式对象实现不同颜色、大小和样式的弹幕效果。
<div
v-for="(item, index) in danmuList"
:key="index"
class="danmu-item"
:class="`danmu-type-${item.type}`"
:style="{
top: `${item.top}px`,
left: `${item.x}px`,
color: item.color,
fontSize: `${item.size}px`
}"
>
{{ item.text }}
</div>
弹幕交互功能
添加鼠标悬停暂停、点击事件等交互功能,提升用户体验。
methods: {
pauseDanmu(index) {
this.danmuList[index].paused = true;
},
resumeDanmu(index) {
this.danmuList[index].paused = false;
}
}
这些方法可以根据实际需求组合使用,实现不同复杂度的平缓弹幕效果。核心在于控制运动轨迹的平滑性和性能优化,确保大量弹幕也能流畅运行。



