Files
product-uniapp/components/danmu/danmu.vue
T
2025-12-12 18:34:44 +08:00

125 lines
2.5 KiB
Vue

<template>
<view class="danmu-container" v-if="visible">
<view
v-for="item in danmuItems"
:key="item.id"
class="danmu-item"
:style="{
top: item.top + 'rpx',
animationDuration: item.speed + 's',
color: item.color
}"
>
{{ item.text }}
</view>
</view>
</template>
<script>
export default {
props: {
list: Array,
visible: { type: Boolean, default: true },
row: { type: Number, default: 5 } // 轨道数
},
data() {
return {
danmuItems: [],
laneBusy: [] // 轨道是否被占用
}
},
mounted() {
this.laneBusy = Array(this.row).fill(false)
this.startDanmu()
},
methods: {
startDanmu() {
let index = 0
setInterval(() => {
const text = this.list[index].content
this.createDanmu(text)
index = (index + 1) % this.list.length
}, 1500)
},
createDanmu(text) {
const lane = this.getFreeLane()
const id = Date.now() + Math.random()
const item = {
id,
text,
top: lane * 100, // 每条轨道高度 60rpx
speed: 6 + Math.random()*2,
color: this.randomColor(),
lane
}
this.danmuItems.push(item)
setTimeout(() => {
this.finishDanmu(id, lane)
}, item.speed * 1000)
},
getFreeLane() {
// 找到第一个空轨道
for (let i = 0; i < this.row; i++) {
if (!this.laneBusy[i]) {
this.laneBusy[i] = true
return i
}
}
// 如果都满了,就随机一个
return Math.floor(Math.random() * this.row)
},
finishDanmu(id, lane) {
this.danmuItems = this.danmuItems.filter(i => i.id !== id)
// 整个动画跑完后释放轨道
this.laneBusy[lane] = false
},
randomColor() {
const colors = ["#fff", "#00F6FF", "#FFEA00", "#FF66C4"]
return colors[Math.floor(Math.random() * colors.length)]
}
}
}
</script>
<style>
.danmu-container {
position: absolute;
left: 0;
top: 88rpx;
width: 100%;
height: 600rpx;
overflow: hidden;
pointer-events: none;
z-index: 100;
}
.danmu-item {
position: absolute;
right: -400rpx;
font-size: 26rpx;
white-space: nowrap;
animation-name: danmu-move;
animation-timing-function: linear;
animation-fill-mode: forwards;
background: rgb(0 0 0 / 60%);
padding: 5px 14px;
border-radius: 20px;
}
@keyframes danmu-move {
from { transform: translateX(0); }
to { transform: translateX(-1200rpx); }
}
</style>