uniapp微信小程序摇一摇抽奖功能的实现
使用微信提供的wx.startAccelerometer()方法实现,可以写在onShow()钩子函数中,当用户摇动手机时会自动触发
具体实现方法如下:
// 开始监听加速度数据。
wx.startAccelerometer({
interval: 'game',
success: function() {
// 监听加速度数据事件。频率根据 wx.startAccelerometer() 的 interval 参数, 接口调用后会自动开始监听。
wx.onAccelerometerChange(function(res) {
// res.x、res.y、res.z设备偏移量
if (res.x > 3 || res.y > 3 || res.z > 3) {
// _this.loading触发摇一摇时,加载接口,当加载接口获取抽奖结果时,不再触发摇一摇获取抽奖结果的接口
if (!_this.loading) {
//_this.imgPlay为class属性,添加摇一摇的css动画属性
_this.imgPlay = 'play'
// 定时器去除摇一摇的css样式
setTimeout(() => {
// 计时器去除摇一摇的css样式
_this.imgPlay = ''
_this.loading = false
// _this.getDrawRaffle()是调用抽奖结果的方法
_this.getDrawRaffle()
}, 1000)
_this.loading = true
}
} else {
uni.showToast({
title: '今天抽奖次数已用完',
duration: 2000,
icon: 'none'
})
}
})
}
})