vue实现发送弹幕
Vue 实现发送弹幕功能
创建弹幕组件
在 Vue 项目中创建一个弹幕组件 Danmu.vue,用于显示和管理弹幕。组件包含弹幕容器和发送弹幕的表单。
<template>
<div class="danmu-container">
<div class="danmu-display" ref="danmuDisplay">
<div
v-for="(danmu, index) in danmuList"
:key="index"
class="danmu-item"
:style="{
top: `${danmu.top}px`,
color: danmu.color,
fontSize: `${danmu.size}px`,
}"
>
{{ danmu.text }}
</div>
</div>
<div class="danmu-input">
<input v-model="inputText" placeholder="输入弹幕内容" />
<button @click="sendDanmu">发送</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
inputText: "",
danmuList: [],
colors: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"],
};
},
methods: {
sendDanmu() {
if (!this.inputText.trim()) return;
const danmu = {
text: this.inputText,
top: Math.random() * 200,
color: this.colors[Math.floor(Math.random() * this.colors.length)],
size: Math.floor(Math.random() * 10 + 14),
};
this.danmuList.push(danmu);
this.inputText = "";
setTimeout(() => {
this.danmuList.shift();
}, 5000);
},
},
};
</script>
<style>
.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
border: 1px solid #ccc;
}
.danmu-display {
position: relative;
width: 100%;
height: 100%;
}
.danmu-item {
position: absolute;
white-space: nowrap;
animation: move 10s linear;
}
@keyframes move {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
.danmu-input {
margin-top: 10px;
}
</style>
使用弹幕组件
在父组件中引入并使用弹幕组件,确保弹幕功能可以正常工作。
<template>
<div>
<Danmu />
</div>
</template>
<script>
import Danmu from "./Danmu.vue";
export default {
components: {
Danmu,
},
};
</script>
弹幕动画优化
通过 CSS 动画控制弹幕的移动速度和方向,确保弹幕从右向左平滑移动。
.danmu-item {
animation: move 10s linear;
}
@keyframes move {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
弹幕随机样式
为弹幕添加随机颜色、大小和垂直位置,增强视觉效果。
const danmu = {
text: this.inputText,
top: Math.random() * 200,
color: this.colors[Math.floor(Math.random() * this.colors.length)],
size: Math.floor(Math.random() * 10 + 14),
};
弹幕自动清理
设置定时器自动清理过期的弹幕,防止弹幕列表无限增长。
setTimeout(() => {
this.danmuList.shift();
}, 5000);






