先上效果图
概述:
弹幕自动播放,所有弹幕播放完毕可继续循环播放,也可只播放一轮。弹幕参数可自定义添加,比如想在弹幕文字前面显示用户头像,只需在constructor中添加参数,调用时赋值即可,废话不多说,直接上代码
<!--index.wxml-->
<view class="doommview">
<block wx:for="{{doommData}}" wx:key="id">
<text wx:if="{{item.display}}" class="aon" style="animation: first {{item.time}}s linear forwards;top:{{item.top}}%;color:{{item.color}};">
{{item.text}}
</text>
</block>
</view>
<view class="button">
<button bindtap="bindbt">弹一个弹幕</button>
</view>
/**index.wxss**/
.button{
position: absolute;
bottom: 0;
width: 100%;
}
.aon{
position: absolute;
white-space:nowrap;/* 防止向下换行*/
animation-timing-function: linear;
animation-fill-mode: none;
}
.doommview{
z-index: 3;
height: 80%;
width: 100%;
position: absolute;
}
@keyframes first{
from{left: 100%; }
to{left: -100%;}
}
//index.js
var that = undefined;
var doommList = [];
var i = 0;
var ids=0;
var cycle=null //计时器
// 弹幕参数
class Doomm {
constructor(text, top, time, color) { //内容,顶部距离,运行时间,颜色(参数可自定义增加)
this.text = text;
this.top = top;
this.time = time;
this.color = color;
this.display = true;
this.id = i++;
}
}
// 弹幕字体颜色
function getRandomColor() {
let rgb = []
for (let i = 0; i < 3; ++i) {
let color = Math.floor(Math.random() * 256).toString(16)
color = color.length == 1 ? '0' + color : color
rgb.push(color)
}
return '#' + rgb.join('')
}
Page({
data: {
doommData: [],
arr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
},
onLoad: function () {
that = this;
cycle= setInterval(function () {
let arr=that.data.arr
if(arr[ids]==undefined){
ids = 0
// 1.循环一次,清除计时器
// doommList = []
// clearInterval(cycle)
// 2.无限循环弹幕
doommList.push(new Doomm(arr[ids], Math.ceil(Math.random() * 100), 5, getRandomColor()));
if(doommList.length>5){ //删除运行过后的dom
doommList.splice(0, 1)
}
that.setData({
doommData: doommList
})
ids++
}else{
doommList.push(new Doomm(arr[ids], Math.ceil(Math.random() * 100), 5, getRandomColor()));
if(doommList.length>5){
doommList.splice(0, 1)
}
that.setData({
doommData: doommList
})
ids++
}
}, 1000)
},
onHide(){
clearInterval(cycle)
ids=0;
doommList=[]
},
onUnload(){
clearInterval(cycle)
ids = 0;
doommList = []
},
bindbt:function(){
doommList.push(new Doomm("这是我的弹幕",Math.ceil(Math.random()*100),Math.ceil(Math.random()*10),getRandomColor()));
this.setData({
doommData : doommList
})
}
})
如有问题请指正,欢迎交流