参考技术分享:https://www.cnblogs.com/mrzll/p/10283272.html
先上效果图
逻辑就是点击抽奖后,需要做一个跑马灯的效果,并且一开始加速然后减速到出中奖结果,这边会用到定时器,每切换一下调用定时器,直到出来结果后清除定时器
wxml
<veiw class="lottery-list weui-flex">
<block wx:for="{{lotteryList}}" wx:key="index">
<view class="lottery-list-item {{_index==index ? 'active' : ''}}" bindtap="begin" data-id="{{item.id}}" data-in="{{index}}">
<image class="bg" src="/images/pic/check.png" mode="aspectFill"></image>
<image wx:if="{{_index==index}}" class="bg bg2" src="/images/pic/checked.png" mode="aspectFill"></image>
<image src="{{item.img}}" mode="heightFix"></image>
</view>
</block>
</veiw>
js
data: {
_index: undefined, // 当前转动位置,
_curId: 3, // 中奖的id 后台提供
_speed: 60, // 转动的速度
isClick: false, // 抽奖中状态
times: 0, // 转动的次数
arr: [1,3,6,8] // 测试数据,提供几个不中奖的id
},
begin:function(e) {
// 根据index判断点击按钮为立即抽奖按钮
if (e.currentTarget.dataset.in == 4) {
this.startGame()
}
},
startGame:function() {
if(!this.data._isClick) {
if (this.data.times == 0) {
this.setData({
_isClick: true,
_index: 0,
_curId: this.data.arr[Math.ceil(3*Math.random())]
})
} else {
this.setData({
_isClick: true,
_speed: 60,
times:0,
_curId: this.data.arr[Math.ceil(3*Math.random())]
})
}
setTimeout(()=>{
this.roll();
}, this.data._speed)
} else{
wx.showToast({
title: '上次抽奖未结束',
icon: 'none'
})
}
},
roll:function() {
var newIndex
// 需要实现跑马灯效果,所以需要判断一下下一步的 _index
switch (this.data._index) {
case 2:
newIndex = 5
break;
case 5:
newIndex = 8
break;
case 8:
newIndex = 7
break;
case 7:
newIndex = 6
break;
case 6:
newIndex = 3
break;
case 3:
newIndex = 0
break;
default:
newIndex = this.data._index + 1
break;
}
let times = this.data.times + 1
this.setData({
_index: newIndex,
times: times
})
if(times > 14 && this.data._curId == this.data.lotteryList[newIndex].id) { // 转动圈数超过基数+10 并且当前位置等于中奖结果位置
clearTimeout(timer); // 清除定时器
this.setData({
_isClick: false
})
// 接下来展示中奖结果
...
} else {
if(times < 6) { // 圈数小于设置的基数 速度边快
this.setData({
_speed: this.data._speed -= 10
})
} else {
var newIndex2
switch (newIndex + 1) {
case 2:
newIndex2 = 5
break;
case 5:
newIndex2 = 8
break;
case 8:
newIndex2 = 7
break;
case 7:
newIndex2 = 6
break;
case 6:
newIndex2 = 3
break;
case 3:
newIndex2 = 0
break;
default:
newIndex2 = newIndex + 1
break;
}
// 每转一圈加速 (加减速这块没有处理的很好)
if (times > 14 && newIndex == 3){
this.setData({
_speed: this.data._speed += 110
})
} else {
this.setData({
_speed: this.data._speed += 20
})
}
}
if (this.data._speed < 60) { // 设置最快速度
this.setData({
_speed : 60
})
}
var timer = setTimeout(()=>{ // 重复执行
this.roll();
}, this.data._speed)
}
}