前言
今天主要介紹一下html5重力感應事件之DeviceMotionEvent,之前我的一篇文章http://www.haorooms.com/post/jquery_jGestures, 介紹了第三方封裝的事件,里面的“orientationchange”可以獲取設備方向的改變。今天主要介紹一下html5自帶的事件,不過,這個事件是新的事件,關於文檔請看:http://w3c.github.io/deviceorientation/spec-source-orientation.html
事件介紹
1、deviceorientation 提供設備的物理方向信息,表示為一系列本地坐標系的旋角。
2、devicemotion 提供設備的加速信息,表示為定義在設備上的坐標系中的卡爾迪坐標。其還提供了設備在坐標系中的自轉速率。若可行的話,事件應該提供設備重心處的加速信息。
3、compassneedscalibration 用於通知Web站點使用羅盤信息校准上述事件。
用法簡介
注冊一個deviceorientation事件的接收器:
window.addEventListener("deviceorientation", function(event) { // 處理event.alpha、event.beta及event.gamma }, true);
將設備放置在水平表面,屏幕頂端指向西方,則其方向信息如下:
{alpha: 90, beta: 0, gamma: 0};
為了獲得羅盤指向,可以簡單的使用360度減去alpha。若設被平行於水平表面,其羅盤指向為(360 - alpha)。 若用戶手持設備,屏幕處於一個垂直平面且屏幕頂端指向上方。beta的值為90,alpha和gamma無關。 用戶手持設備,面向alpha角度,屏幕處於一個垂直屏幕,屏幕頂端指向右方,則其方向信息如下:
{alpha: 270 - alpha, beta: 0, gamma: 90};
只用自定義界面通知用戶校准羅盤:
window.addEventListener("compassneedscalibration", function(event) { alert('您的羅盤需要校准,請將設備沿數字8方向移動。'); event.preventDefault(); }, true);
注冊一個devicemotion時間的接收器:
window.addEventListener("devicemotion", function(event) { // 處理event.acceleration、event.accelerationIncludingGravity、 // event.rotationRate和event.interval }, true);
將設備放置在水平表面,屏幕向上,acceleration為零,則其accelerationIncludingGravity信息如下:
{x: 0, y: 0, z: 9.81};
設備做自由落體,屏幕水平向上,accelerationIncludingGravity為零,則其acceleration信息如下:
{x: 0, y: 0, z: -9.81};
將設備安置於車輛至上,屏幕處於一個垂直平面,頂端向上,面向車輛后部。車輛行駛速度為v,向右側進行半徑為r的轉彎。設備記錄acceleration和accelerationIncludingGravity在位置x處的情況,同時設備還會記錄rotationRate.gamma的負值:
{acceleration: {x: v^2/r, y: 0, z: 0}, accelerationIncludingGravity: {x: v^2/r, y: 0, z: 9.81}, rotationRate: {alpha: 0, beta: 0, gamma: -v/r*180/pi} };
應用案例
if (window.DeviceMotionEvent) { window.addEventListener('devicemotion',deviceMotionHandler, false); } var speed = 30;//speed var x = y = z = lastX = lastY = lastZ = 0; function deviceMotionHandler(eventData) { var acceleration =eventData.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) { //簡單的搖一搖觸發代碼 alert(1); } lastX = x; lastY = y; lastZ = z; }
計步功能:
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion',deviceMotionHandler, false);
}
var SHAKE_THRESHOLD = 800;
var last_update = 0;
var x, y, z, last_x, last_y, last_z;
function deviceMotionHandler(eventData) {
var acceleration =eventData.accelerationIncludingGravity;
//alert(newDate().getTime());
var curTime = new Date().getTime();
// alert(curTime - last_update);
if ((curTime - last_update)> 300) {
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;
if (speed > SHAKE_THRESHOLD) {
alert("shaked!");
}
last_x = x;
last_y = y;
last_z = z;
}
}
