先看效果图
实现效果:
- 每个红包的image大小不一样
- 每个红包的旋转角度不一样
- 每个红包的下落速度不一样
- 每个红包的位置不一样
如何实现?
- 在页面上我们用wx:for函数遍历js中的红包数组,如下:
<view class='content'>
<view class="hongbaoView" >
<block wx:for="{{hongbaoArr}}" wx:for-item="item">
<image style="transform:rotate({{item.jiaodu}}deg);margin-left:{{item.marginleft}}rpx;width:{{item.width}}rpx;height:{{item.height}}rpx;animation: dropdown {{item.animation}}s;animation-fill-mode:forwards;" class="hongbao" src='../images/红包.png' data-id='{{item.id}}' id="hongbao_{{item.id}}" bindtap='qianghongbao'></image>
</block>
</view>
</view>
在image的style中,有几个参数是随机数,其中
- transform:rotate({{item.jiaodu}}deg);该参数为红包的旋转角度;
-
margin-left:{{item.marginleft}}rpx;该参数为左边距,即红包的位置;
-
width:{{item.width}}rpx;height:{{item.height}}rpx;这两个参数是红包的大小,由于红包的图片是32*32的,所以在JS中width=height,这样能保证红包图片不会变形;
-
animation: dropdown {{item.animation}}s;该参数为红包下路的时间,下落时间不一样就能达到下落速度不一样的效果;
- 在JS中我们需要随机生成红包,并push到红包数组中,完整JS如下:
// pages/news/news.js
Page({
data: {
hongbaoArr:null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getHongbao(1);
},
getHongbao:function(i){
var shijian = Math.floor(Math.random() * (200-100)+100);
var jiaodu = Math.ceil(Math.random() * 30)-15;
var marginLeft = Math.ceil(Math.random() * 690);
var width = Math.floor(Math.random() * (100 - 60 + 1) + 60);
var animation = Math.floor(Math.random() * (6-3)+3)
console.log(marginLeft);
var hongbao = {
id: i,
jiaodu: jiaodu,
marginleft: marginLeft,
width: width,
height: width,
animation: animation
}
var hongbaoA = this.data.hongbaoArr;
if (hongbaoA == null){
hongbaoA = new Array();
}
hongbaoA.push(hongbao);
this.setData({
hongbaoArr: hongbaoA
})
var that = this;
if(i <= 100){
var timerTem =setTimeout(function () {
i = i+ 1;
console.log(i);
that.getHongbao(i)
}, shijian)
}
},
qianghongbao:function(e){
var id = e.currentTarget.dataset['id'];
var query = wx.createSelectorQuery();
var hongbao = query.select("#"+id);
console.log(hongbao);
hongbao.classList.remove('animate');
}
})
下面讲解一下JS
- data中的hongbaoArr即为我们的红包数组;
- 在页面加载时调用getHongbao函数来获取红包;
- 在getHongbao中先获取几个随机数,其中var shijian = Math.floor(Math.random() * (200-100)+100);这个为每生成一个红包需要等待shijian毫秒的时间才会生成下一个红包;
-
if(i <= 100){
var timerTem =setTimeout(function () {
i = i+ 1;
console.log(i);
that.getHongbao(i)
}, shijian)
}该段代码控制生成100个红包,采用递归的方式
-
qianghongbao这个函数请忽略
- CSS中我们只需写一些很简单样式就好
.hongbao{
position: absolute;
}
@keyframes dropdown {
from{margin-top: -50rpx;}
to{margin-top: 1200rpx;}
}
比较简单就不赘述了。
打开红包效果见微信小程序打开红包效果