小程序弹幕效果,可无限循环

先上效果图
在这里插入图片描述

概述:

弹幕自动播放,所有弹幕播放完毕可继续循环播放,也可只播放一轮。弹幕参数可自定义添加,比如想在弹幕文字前面显示用户头像,只需在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
    })
  }
})




如有问题请指正,欢迎交流

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值