Created
October 24, 2019 02:02
-
-
Save hallee9000/637ac359e3f3f1d4eb404b076b657bd8 to your computer and use it in GitHub Desktop.
微信小程序摇一摇代码
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 首先定义一下,全局变量 | |
let lastTime = 0; // 此变量用来记录上次摇动的时间 | |
let x = 0, | |
y = 0, | |
z = 0, | |
lastX = 0, | |
lastY = 0, | |
lastZ = 0; // 此组变量分别记录对应x、y、z三轴的数值和上次的数值 | |
let shakeSpeed = 30; // 设置阈值 | |
// 编写摇一摇方法 | |
export default function shake(callback) { | |
function shakeHandler(acceleration) { | |
const nowTime = new Date().getTime(); // 记录当前时间 | |
// 如果这次摇的时间距离上次摇的时间有一定间隔 才执行 | |
if (nowTime - lastTime > 200) { | |
const diffTime = nowTime - lastTime; // 记录时间段 | |
lastTime = nowTime; // 记录本次摇动时间,为下次计算摇动时间做准备 | |
x = acceleration.x; // 获取x轴数值,x轴为垂直于北轴,向东为正 | |
y = acceleration.y; // 获取y轴数值,y轴向正北为正 | |
z = acceleration.z; // 获取z轴数值,z轴垂直于地面,向上为正 | |
// 计算 公式的意思是 单位时间内运动的路程,即为我们想要的速度 | |
const speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000; | |
if (speed > shakeSpeed) { // 如果计算出来的速度超过了阈值,那么就算作用户成功摇一摇 | |
callback && callback() | |
} | |
lastX = x; // 赋值,为下一次计算做准备 | |
lastY = y; // 赋值,为下一次计算做准备 | |
lastZ = z; // 赋值,为下一次计算做准备 | |
} | |
} | |
wx.onAccelerometerChange(shakeHandler) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment