微信小程序实现抽奖大轮盘
最近遇到做活动抽奖要用转盘,记录下做个笔记。
xml部分:
<view class="draw-container"> <view class="draw-table-box"> <image animation="{ {animationData}}" src="{ {tableBg}}" class="draw-table-bg"/> <image bindtap="tableroll" src="{ {go}}" class="draw-table-go { {times?:draw-table-go-grey}}"/> </view> <view>剩余抽奖次数: { {times}}</view> </view>
css部分:
.draw-container { display: flex; flex-direction: column; align-items: center; margin-top: 40rpx; } .draw-table-box { width: 556rpx; height: 558rpx; position: relative; } .draw-table-bg { width: 100%; height: 100%; top: 0; left: 0; } .draw-table-go { width: 148rpx; height: 192rpx; position: absolute; z-index: 1; top: 50%; left: 50%; transform: translate(-50%, -50%); } .draw-table-go-grey { filter: grayscale(100%); filter: gray; }
js部分:
Page({ data: { tableBg: https://o3pvuu23u.qnssl.com/2f9bddd9-bb82-47ed-bd0f-9b1bee4463b8.png, go: https://o3pvuu23u.qnssl.com/e36952f5-0458-467b-890c-61941877c0c9.png, animationData: {}, singleDeg: 60, //单个奖项的角度 i: 4, // 自测中奖初始值 initDeg: 0, awards: [ {id: 6, degree: 6等奖, name: iphone xs}, {id: 3, degree: 1等奖, name: 50积分}, {id: 4, degree: 2等奖, name: 10积分}, {id: 5, degree: 3等奖, name: 5积分}, {id: 2, degree: 4等奖, name: 2积分}, {id: 1, degree: 5等奖, name: 1积分}, ], times: 3, isClick: false, // 转盘转动时防止用户再次点击抽奖 }, onLoad() { }, onShow() { // 创建一个动画实例 var animation = wx.createAnimation({ duration: 2000, timingFunction: ease, }) this.animation = animation }, tableroll() { if(this.data.isClick) return if(this.data.times<1) return console.log(触发抽奖=====) this.setData({ isClick: true }) let randomNum = Math.random() let deviation = randomNum > 0.5 ? randomNum - 0.1 : randomNum + 0.1 this.mockDrawInfo().then((result) => { let res1 = this.data.awards.filter((item)=> { return item.degree == result.degree }) this.data.i++ if(this.data.i===7) { this.data.i = 1 } console.log(mockDrawInfo==result=======res1[0], result, res1[0]) let rotateDeg = 60 * (res1[0].id - deviation) + 360 console.log(rotateDeg===, rotateDeg, res1[0].id) let surplusDeg = (Math.floor(Math.random()*4) + 4) * 360 this.animation.rotate(this.data.initDeg + rotateDeg + surplusDeg).step() this.data.initDeg += surplusDeg this.setData({ animationData: this.animation.export(), }) setTimeout(() => { this.setData({ isClick: false, times:--this.data.times, }) }, 2000) }) }, // 模拟中奖信息接口返回数据 mockDrawInfo() { return new Promise((resolve, reject) => { setTimeout(() => { resolve({degree: this.data.i+等奖}) }, 1000) }) } })
上一篇:
uniapp开发微信小程序-2.页面制作