vue实现弹幕
Vue 实现弹幕功能
弹幕功能通常包括动态生成、滚动显示、颜色和速度随机化等特性。以下是基于 Vue 3 的实现方法。
核心思路
- 使用 CSS 动画控制弹幕从右向左滚动。
- 动态生成弹幕数据,随机设置样式(颜色、速度、位置)。
- 通过 Vue 的
v-for指令渲染弹幕列表。
实现步骤
模板部分
<template>
<div class="danmu-container">
<div
v-for="(item, index) in danmuList"
:key="index"
class="danmu-item"
:style="{
top: item.top + 'px',
color: item.color,
animationDuration: item.duration + 's'
}"
>
{{ item.text }}
</div>
<input v-model="inputText" @keyup.enter="sendDanmu" placeholder="输入弹幕内容" />
</div>
</template>
样式部分
.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
background: #000;
}
.danmu-item {
position: absolute;
white-space: nowrap;
animation: danmuMove linear;
font-size: 16px;
user-select: none;
}
@keyframes danmuMove {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
脚本部分
<script>
import { ref } from 'vue'
export default {
setup() {
const danmuList = ref([])
const inputText = ref('')
// 生成随机颜色
const getRandomColor = () => {
const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff']
return colors[Math.floor(Math.random() * colors.length)]
}
// 发送弹幕
const sendDanmu = () => {
if (!inputText.value.trim()) return
danmuList.value.push({
text: inputText.value,
color: getRandomColor(),
top: Math.random() * 250, // 随机垂直位置
duration: 5 + Math.random() * 5 // 随机速度
})
inputText.value = ''
}
// 模拟自动生成弹幕
setInterval(() => {
const texts = ['666', '太棒了', '哈哈哈', '学到了', 'Vue真好用']
danmuList.value.push({
text: texts[Math.floor(Math.random() * texts.length)],
color: getRandomColor(),
top: Math.random() * 250,
duration: 5 + Math.random() * 5
})
}, 1000)
return {
danmuList,
inputText,
sendDanmu
}
}
}
</script>
优化建议
-
性能优化
弹幕数量过多时移除已滚出屏幕的弹幕元素:// 在动画结束后移除弹幕 const handleAnimationEnd = (index) => { danmuList.value.splice(index, 1) } -
自定义配置
添加配置选项控制弹幕密度、速度范围等参数。 -
WebSocket 集成
结合 WebSocket 实现实时弹幕功能,适合直播等场景。 -
防遮挡处理
通过算法避免弹幕重叠,提升可读性。 -
移动端适配
针对移动设备调整弹幕大小和速度。
以上实现提供了弹幕功能的基础框架,可根据实际需求进行扩展和优化。







