复制代码代码如下: if (window.DeviceMotionEvent) { window.addEventListener( devicemotion ,deviceMotionHandler, false); }
2. [代码]获取含重力的加速度
复制代码代码如下: function deviceMotionHandler(eventData) { var acceleration =eventData.accelerationIncludingGravity; }
3. [代码]核心方法实现代码
复制代码代码如下: var SHAKE_THRESHOLD = xxx; var last_update = 0; var x, y, z, last_x, last_y, last_z; /p p function deviceMotionHandler(eventData) { var acceleration =eventData.accelerationIncludingGravity; /p p var curTime = newDate().getTime(); /p p if ((curTime lastUpdate) 100) { /p p var diffTime = curTime -last_update; last_update = curTime; /p p x = acceleration.x; y = acceleration.y; z = acceleration.z; /p p var speed = Math.abs(x +y + z last_x last_y last_z) / diffTime * 10000; /p p if (speed SHAKE_THRESHOLD) { alert( shaked! ); } last_x = x; last_y = y; last_z = z; } } html教程