html5搖一搖功能的實現

經過網上的資料,加上本身的整理。html

寫份html搖一搖功能的簡介,用作技術備份。
 
知識要點
 
DeviceMotionEvent
    這是html5支持的重力感應事件, 關於文檔請看: http://w3c.github.io/deviceorientation/spec-source-orientation.html
事件介紹:
  • deviceorientation 提供設備的物理方向信息,表示爲一系列本地座標系的旋角。
  • devicemotion 提供設備的加速信息,表示爲定義在設備上的座標系中的卡爾迪座標。其還提供了設備在座標系中的自轉速率。若可行的話,事件應該提供設備重心處的加速信息。
  • compassneedscalibration 用於通知Web站點使用羅盤信息校準上述事件。
事件簡介
 window.addEventListener("deviceorientation",function(event){// 處理event.alpha、event.beta及event.gamma},true);

{alpha:90,
   beta:0,
   gamma:0};

 

這是  deviceorientation事件返回的參數,爲了得到羅盤指向,能夠簡單的使用360度減去alpha。若設被平行於水平表面,其羅盤指向爲(360 - alpha)。 若用戶手持設備,屏幕處於一個垂直平面且屏幕頂端指向上方。beta的值爲90,alpha和gamma無關。 用戶手持設備,面向alpha角度,屏幕處於一個垂直屏幕,屏幕頂端指向右方,則其方向信息以下
{alpha:270- alpha,
   beta:0,
   gamma:90};

 

 
註冊一個devicemotion事件的接收器:
window.addEventListener("devicemotion",function(event){// 處理event.acceleration、event.accelerationIncludingGravity、// event.rotationRate和event.interval},true);

 

 
將設備安置於車輛之上,屏幕處於一個垂直平面,頂端向上,面向車輛後部。車輛行駛速度爲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}};

 

 
功能實現
 1     if(window.DeviceMotionEvent){
 2     window.addEventListener('devicemotion', YaoYiYao,false);
 3     }
 4     var speed =30;//speed
 5     var x = y = z = lastX = lastY = lastZ =0;
 6     function YaoYiYao(eventData){
 7     var acceleration =eventData.accelerationIncludingGravity;
 8     x = acceleration.x;
 9     y = acceleration.y;
10     z = acceleration.z;
11     if(Math.abs(x-lastX)> speed ||Math.abs(y-lastY)> speed ||Math.abs(z-lastZ)> speed){
12     //簡單的搖一搖觸發代碼
13     alert(1);
14     }
15     lastX = x;
16     lastY = y;
17     lastZ = z;
18     }

 

首先判斷瀏覽器是否支持該事件。
YaoYiYao用來檢測是否對手機進行搖動操做,具體就是獲取手機的的移動數據,將其存在一個外部變量中,當下次又觸發搖動事件時,判斷上次的搖動座標 和如今的搖動座標 是否處於一個頻繁調動的範圍: Math . abs ( x - lastX ) > speed || Math . abs ( y - lastY ) > speed || Math . abs ( z - lastZ ) > speed
基本上 知足這種條件的話,就是手機正處於搖動狀態,在if語句裏面添加進你要執行的搖一搖代碼便可。
相關文章
相關標籤/搜索