怎么在微信小程序中实现红包雨功能

发布时间:2021-05-22 17:17:39 作者:Leah
来源:亿速云 阅读:599

今天就跟大家聊聊有关怎么在微信小程序中实现红包雨功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

wxml:

<view wx:for="{{packetList}}" wx:for-index="index" wx:for-item="items">
 <image class="red-packet" src="{{items.src}}" >
 </image>
</view>

wxss:

.red-packet{
 width: 20px;
 height: 25px;
 z-index: 100;
 transition-property:transform,top;
 transform-origin:50% 50% 0;
 -webkit-transition-property:transform,top;
 -webkit-transform-origin:50% 50% 0;
}

js:

Page({
 
 /**
 * 页面的初始数据
 */
 data: {
 windowWidth:"",//窗口宽度
 windowHeigh:"",//窗口高度
 packetList:[{}],//红包队列
 packetNum:200,//总共红包的数量
 showInter:''// 循环动画定时器
 },
 
 /**
 * 生命周期函数--监听页面加载
 */
 onLoad: function (options) {
 var that = this;
 
 // 获取手机屏幕宽高
 wx.getSystemInfo({
  success: function (res) {
  that.setData({
   windowWidth: res.windowWidth,
   windowHeigh: res.windowHeight,
   top: res.windowHeight-100 //设置红包初始位置
  })
  }
 })
 
 //建立临时红包列表
 var packetList=[];
 //建立临时红包图片数组
 var srcList = ["../images/packet-one.png", "../images/packet-two.png"];
 //生成初始化红包
 for(var i=0;i<that.data.packetNum;i++){
  // 生成随机位置(水平位置)
  var left = Math.random() * that.data.windowWidth-20;
  // 优化位置,防止红包越界现象,保证每个红包都在屏幕之内
  if(left<0){
  left+=20;
  } else if (left > that.data.windowWidth){
  left-=20;
  }
  // 建立临时单个红包
  var packet = {
  src: srcList[Math.ceil(Math.random() * 2) - 1],
  top: -30,
  left:left,
  speed:Math.random() * 2500+3000  //生成随机掉落时间,保证每个掉落时间保持在3秒到5.5秒之间
  }
  // 将单个红包装入临时红包列表
  packetList.push(packet);
  // 将生成的临时红包列表更新至页面数据,页面内进行渲染
  that.setData({
  packetList: packetList
  })
 }
 
 // 初始化动画执行当前索引
 var tempIndex=0;
 // 开始定时器,每隔1秒掉落一次红包
 that.data.showInter=setInterval(function(){
  // 生成当前掉落红包的个数,1-3个
  var showNum = Math.ceil(Math.random() * 3);
  // 防止数组越界
  if (tempIndex * showNum>=that.data.packetNum){
  // 如果所有预生成的红包已经掉落完,清除定时器
  clearInterval(that.data.showInter);
  }else{
  switch (showNum){
   case 1:
   //设置临时红包列表当前索引下的top值,此处top值为动画运动的最终top值 
   packetList[tempIndex].top = that.data.windowHeigh;
   // 当前次掉落几个红包,索引值就加几
   tempIndex+=1;
   break;
   case 2:
   packetList[tempIndex].top = that.data.windowHeigh;
   packetList[tempIndex + 1].top = that.data.windowHeigh;
   tempIndex+=2;
   break;
   case 3:
   packetList[tempIndex].top = that.data.windowHeigh;
   packetList[tempIndex + 1].top = that.data.windowHeigh;
   packetList[tempIndex + 2].top = that.data.windowHeigh;
   tempIndex += 3;
   break;
   default:
   console.log();
  }
  // 更新红包列表数据
  that.setData({
   packetList: packetList
  })
  }
 },1000)
 }
})

看完上述内容,你们对怎么在微信小程序中实现红包雨功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. 小程序红包雨的实现示例
  2. 怎么在微信小程序中实现评论功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

微信小程序

上一篇:怎么在微信小程序中实现倒计时功能

下一篇:使用jquery怎么实现搜索框功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》