H5重力感应事件:
deviceorientation提供设备的物理方向信息
devicemotion提供设备的加速信息
例子:
//摇一摇
if(window.DeviceMotionEvent){
window.addEventListener('devicemotion',deviceMotionHandler,false);
}else{
alert('您的设备不支持该功能');
}
var SHAKE_THRESHOLD = 800;
var last_update = 0;
var x, y, z, lastX, lastY, lastZ;
var count = 0;
var lock = true;
function deviceMotionHandler(eventData){
var acceleration = eventData.accelerationIncludingGravity;
var curTime = new Date().getTime();
if((curTime - last_update) > 300 && lock){
var diffTime = curTime - last_update;
last_update = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
var speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000;
if(speed > SHAKE_THRESHOLD){
lock = false;
setTimeout(function(){
lock = true;
},2000)
alert(count++);
}
lastX = x;
lastY = y;
lastZ = z;
}
}
参考链接:
http://segmentfault.com/a/1190000003095883