H5實現的手機搖一搖

y637 9年前發布 | 15K 次閱讀 JavaScript HTML5

    <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="status"></div>
</body>
<script>
var shake=4000,
last_update=0,
count=0,
x=y=z=last_x=last_y=last_z=0;
if(window.DeviceMotionEvent){
window.addEventListener("devicemotion",deviceMotionHandler,false);
}else{
alert("本設備不支持devicemotion事件");
}
console.log(new Date().valueOf());
function deviceMotionHandler(eventData){
var acceleration = eventData.accelerationIncludingGravity,
currTime=new Date().valueOf(),
diffTime=currTime-last_update;

                if(diffTime>100){  
                   last_update=currTime;  
                   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){  
                         count++;  
                         status.innerHTML = "你搖了中"+count+"次" ;  
                   }  
                   last_x = x;  
                   last_y = y;  
                   last_z = z;  
                }  
       }  
    </script>  
</html>  </pre> 


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.

真個代碼的解析就是這樣了。

 本文由用戶 y637 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!