在HTML5中,DeviceOrientation特性所提供的DeviceMotion事件封裝了設備的運動傳感器時間,經過改時間能夠獲取設備的運動狀態、加速度等數據(另還有deviceOrientation事件提供了設備角度、朝向等信息)。
而經過DeviceMotion對設備運動狀態的判斷,則能夠幫助咱們在網頁上就實現「搖一搖」的交互效果。spa
運動事件監聽code
if (window.DeviceMotionEvent) { window.addEventListener('devicemotion', deviceMotionHandler, false); } else { alert('你的手機太差了,買個新的吧。'); }
獲取加速度信息
「搖一搖」的動做既「必定時間內設備了必定距離」,所以經過監聽上一步獲取到的x, y, z 值在必定時間範圍內的變化率,便可進行設備是否有進行晃動的判斷。而爲了防止正常移動的誤判,須要給該變化率設置一個合適的臨界值。blog
function deviceMotionHandler(eventData) { var acceleration = eventData.accelerationIncludingGravity; var curTime = new Date().getTime(); if ((curTime - last_update) > 100) { var diffTime = curTime - last_update; last_update = curTime; x = acceleration.x; y = acceleration.y; z = acceleration.z; var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000; var status = document.getElementById("status"); if (speed > SHAKE_THRESHOLD) { doResult(); } last_x = x; last_y = y; last_z = z; } }
效果如圖所示:事件