微信小程序实现弹幕效果

  • Post author:
  • Post category:小程序

微信小程序实现弹幕效果

折腾了一周的微信小程序,一直在寻找弹幕效果,但是由于微信小程序的MVVM架构,很多HTML代码都无法运行,只有自己折腾一个出来。
效果:
弹幕效果

主要原理是使用的CSS3的动画效果。
wxml代码:

<!--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>

wxss:

/**index.wxss**/
.button{
  position: absolute;
  bottom: 0;
  width: 100%;
}
.aon{
position: absolute;
white-space:nowrap;/* 防止向下换行*/
}
.doommview{
  z-index: 3;
  height: 80%;
  width: 100%;
  position: absolute;
}
/**定义从右边向左边的移动的动画**/
@keyframes first{
  from{left: 100%; }
  to{left: -100%;}
}

js:

//index.js
var page = undefined;
Page({
  onLoad: function () {
    page = this;
  },
  bindbt:function(){
    doommList.push(new Doomm("你是我的小苹果",Math.ceil(Math.random()*100),Math.ceil(Math.random()*10),getRandomColor()));
    this.setData({
      doommData : doommList
    })
  },
  data: {
    doommData:[]
  }
})
var doommList=[];
var i=0;//用做唯一的wx:key
class Doomm{
  constructor(text,top,time,color){
    this.text = text+i;
    this.top = top;
    this.time = time;
    this.color = color;
    this.display = true;
    let that = this;
    this.id = i++;
    setTimeout(function(){
      doommList.splice(doommList.indexOf(that),1);//动画完成,从列表中移除这项
      page.setData({
      doommData : doommList
    })
    },this.time*1000)//定时器动画完成后执行。
  }
}
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('')
}

这样就可以实现一个弹幕效果,程序还有很多问题,还请各位看官见谅并指正。
项目地址:https://github.com/wjq1028/doomm


版权声明:本文为wjq1028cs2原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。