vue实现弹幕移动效果
实现弹幕移动效果的方法
在Vue中实现弹幕移动效果,可以通过CSS动画或JavaScript动态计算位置来实现。以下是两种常见的实现方式:
CSS动画实现
使用CSS的@keyframes和transform属性创建平移动画,结合Vue的动态渲染控制弹幕元素。
<template>
<div class="danmu-container">
<div
v-for="(item, index) in danmuList"
:key="index"
class="danmu-item"
:style="{
top: `${item.top}px`,
animation: `move ${item.speed}s linear forwards`
}"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
danmuList: []
}
},
methods: {
addDanmu(text) {
this.danmuList.push({
text,
top: Math.random() * 200,
speed: 5 + Math.random() * 5
})
setTimeout(() => {
this.danmuList.shift()
}, 6000)
}
}
}
</script>
<style>
.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
}
.danmu-item {
position: absolute;
white-space: nowrap;
color: white;
text-shadow: 1px 1px 2px black;
}
@keyframes move {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
</style>
JavaScript动态计算实现

通过requestAnimationFrame实现更精确的控制,适合需要复杂交互的场景。
<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`
}"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
danmuList: [],
animationId: null
}
},
mounted() {
this.startAnimation()
},
beforeDestroy() {
cancelAnimationFrame(this.animationId)
},
methods: {
addDanmu(text) {
this.danmuList.push({
text,
top: Math.random() * 200,
left: this.$refs.container.offsetWidth,
speed: 2 + Math.random() * 3
})
},
startAnimation() {
const animate = () => {
this.danmuList.forEach(item => {
item.left -= item.speed
})
this.danmuList = this.danmuList.filter(item =>
item.left > -100
)
this.animationId = requestAnimationFrame(animate)
}
animate()
}
}
}
</script>
性能优化建议
对于大量弹幕场景,可以考虑以下优化措施:

使用虚拟滚动技术,只渲染可视区域内的弹幕元素
// 示例代码片段
computed: {
visibleDanmus() {
return this.danmuList.filter(item =>
item.left < this.containerWidth &&
item.left > -item.width
)
}
}
采用Canvas渲染代替DOM操作,大幅提升性能
// 示例代码片段
drawDanmu() {
const ctx = this.$refs.canvas.getContext('2d')
ctx.clearRect(0, 0, width, height)
this.danmuList.forEach(item => {
ctx.fillText(item.text, item.x, item.y)
item.x -= item.speed
})
}
交互增强功能
实现点击暂停、速度调节等交互功能
methods: {
togglePause() {
this.isPaused = !this.isPaused
if (!this.isPaused) {
this.startAnimation()
} else {
cancelAnimationFrame(this.animationId)
}
},
changeSpeed(factor) {
this.danmuList.forEach(item => {
item.speed *= factor
})
}
}
以上实现方式可根据具体需求选择或组合使用,CSS动画方案简单高效,JavaScript方案则提供更多控制灵活性。






