1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 </head> 6 <body> 7 <div id="status"></div> 8 </body> 9 <script> 10 var shake=4000, 11 last_update=0, 12 count=0, 13 x=y=z=last_x=last_y=last_z=0; 14 if(window.DeviceMotionEvent){ 15 window.addEventListener("devicemotion",deviceMotionHandler,false); 16 }else{ 17 alert("本設備不支持devicemotion事件"); 18 } 19 console.log(new Date().valueOf()); 20 function deviceMotionHandler(eventData){ 21 var acceleration = eventData.accelerationIncludingGravity, 22 currTime=new Date().valueOf(), 23 diffTime=currTime-last_update; 24 25 if(diffTime>100){ 26 last_update=currTime; 27 x=acceleration.x; 28 y=acceleration.y; 29 z=acceleration.z; 30 var speed=Math.abs(x+y+z-last_x-last_y-last_z)/diffTime*10000 31 var status=document.getElementById("status"); 32 if(speed>shake){ 33 count++; 34 status.innerHTML = "你搖了中"+count+"次" ; 35 } 36 last_x = x; 37 last_y = y; 38 last_z = z; 39 } 40 } 41 </script> 42 </html>
devicemotion 獲取設備加速度信息。其事件對象返回有3個值,但是我用到的是accelerationIncludingGravity 考慮了重力的影響。地球引力值是9.81 返回的X,Y,Z 其中的Z軸就是9.81 不過有正負之分 水平向上在安卓里面顯示的是是+9.81 在蘋果里面顯示的是-9.81 (最然對於我們的計算沒有影響,但是寫出來讓大家了解一下,免得測試的時候有疑問)。
注意:返回的X,Y,Z的屬性值的單位是m/s^2
acceleration這個屬性是沒有考慮到重力影響的,很奇怪,我也在想為什么出兩個標准。這個難道是考慮在真空嗎。。。。
OK,來說說我們的代碼。
設置了閥值4000(就是當加速度達到了這個值的時候,就觸發了搖一搖的程序)。
獲取上一次的時間last_update.
設置一個count來告訴大家你搖動了幾次。
初始化各個軸的加速讀,以及上一次的加速last_X,last_Y,last_Z.
如果設備支持DeviceMotionEvent就給window進行事件綁定。
獲取當前時間currTime。
獲取當前事件對象的accelerationIncludingGravity屬性。
每100毫秒進行一次獲取和判斷加速度 X,Y,Z。
求的某一次的加速speed是否達到了閥值4000.
如果達到了就出發搖一搖事件。
最后再把這次的X,Y,Z的速度值復制給last_x,y,z.
整個代碼的解析就是這樣了。