廢話不多說(shuō),先上代碼
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion',deviceMotionHandler, false);
}else{
console.log('不支持DeviceMotionEvent');
}
var speed = 20;//speed
var x = y = z = lastX = lastY = lastZ = 0;
function deviceMotionHandler(event) {
var acceleration =event.accelerationIncludingGravity;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed || Math.abs(z-lastZ) > speed) {
//簡(jiǎn)單的搖一搖觸發(fā)代碼
console.log('搖一搖啊');
}
lastX = x;
lastY = y;
lastZ = z;
}
首先判斷瀏覽器是否支持window.DeviceMotionEvent瓶逃,
DeviceMotionEvent為web開(kāi)發(fā)者提供了關(guān)于設(shè)備的位置和方向改變的速度的信息。
如果支持則監(jiān)聽(tīng)devicemotion事件扎拣。如果設(shè)備在X,Y,Z軸方向上有位移腌歉,那么回調(diào)函數(shù)中的參數(shù)event對(duì)象中就會(huì)反應(yīng)出來(lái)。
這里我們用到event對(duì)象中的accelerationIncludingGravity屬性避除,它提供了設(shè)備在X,Y,Z軸方向上帶重力的加速度的對(duì)象怎披。
通過(guò)判斷前后兩次重力加速度差來(lái)判斷手機(jī)是否被搖了。
Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed || Math.abs(z-lastZ) > speed
只要x,y,z軸任意方向滿足條件就判定被搖