实现原理:监听devicemotion事件,通过accelerationIncludingGravity属性获取重力加速度,判断一定时间内重力加速度改变大于某个值,判定为摇动
var SHAKE_THRESHOLD = 4000;//设置判断摇动速度的阀值
var last_update = 0; //记录上次摇动的时间
var x, y, z, last_x = 0, last_y = 0, last_z = 0; //记录三个轴的数据以及上一次触发的时间
var speed; //记录摇动的速度
if (window.DeviceMotionEvent) {
// console.log('支持传感器')
window.addEventListener('devicemotion',this.deviceMotionHandler, false);
}else {
alert('该设备不支持传感器')
}
//运动传感器处理
deviceMotionHandler(eventData){
var acceleration = eventData.accelerationIncludingGravity; //获取重力加速度
var curTime = new Date().getTime(); //获取当前时间
var diffTime = curTime - last_update; //计算时间差
if (diffTime > 300) { //大于某个值时,再执行操作,因为devicemotion随时都在触发,提高性能
last_update = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
if (speed > SHAKE_THRESHOLD) {
// alert('摇到大奖啦!');
//手机震动
// var supportsVibrate = 'vibrate' in navigator;
// if (supportsVibrate) {
// navigator.vibrate(1000);
// }
}
//记录上一次加速度
last_x = x;
last_y = y;
last_z = z;
}
}