摇一摇抽奖uniapp
实现摇一摇抽奖功能的UniApp开发指南
核心依赖技术
- 使用
uni.onAccelerometerChange监听加速度传感器数据 - 通过计算手机摇晃幅度触发抽奖逻辑
- 结合动画效果增强用户体验
加速度传感器监听设置
在onLoad生命周期中启动加速度监听:

onLoad() {
uni.startAccelerometer({
interval: 'game'
});
uni.onAccelerometerChange(this.handleShake);
}
摇晃检测算法实现
创建处理函数计算三维加速度变化:

handleShake(res) {
const { x, y, z } = res;
const speed = Math.abs(x + y + z - this.lastX - this.lastY - this.lastZ);
if (speed > SHAKE_THRESHOLD) {
this.startLottery();
}
this.lastX = x;
this.lastY = y;
this.lastZ = z;
}
抽奖逻辑与动画
实现抽奖核心函数:
startLottery() {
if (this.isShaking) return;
this.isShaking = true;
this.showPrize = false;
// 旋转动画
this.rotateDeg = 0;
const animation = setInterval(() => {
this.rotateDeg += 30;
if (this.rotateDeg >= 3600) {
clearInterval(animation);
this.showResult();
}
}, 50);
}
页面布局结构示例
构建摇奖界面UI:
<template>
<view class="container">
<view
class="turntable"
:style="{transform: `rotate(${rotateDeg}deg)`}"
@click="manualShake"
>
<!-- 奖项分区 -->
</view>
<view v-if="showPrize" class="result-modal">
恭喜获得{{ prizeName }}!
</view>
</view>
</template>
性能优化建议
- 在
onHide生命周期停止传感器监听 - 设置合适的摇动阈值(通常15-20)
- 添加防抖机制防止重复触发
- 使用CSS硬件加速优化动画性能
注意事项
- iOS平台需要描述使用加速度计的用途
- 部分安卓机型需要动态权限申请
- 真机调试时关闭省电模式
- 考虑用户无法摇动手机时的备选操作方案
完整实现应包含奖品概率计算、网络请求对接、用户资格验证等配套功能。实际开发时可根据需求调整动画时长和摇动灵敏度参数。






