首頁  >  文章  >  web前端  >  js 手機搖一搖

js 手機搖一搖

巴扎黑
巴扎黑原創
2016-12-19 14:13:361507瀏覽

上次在玩一手遊看到裡面有一個搖一搖抽獎,遊戲是web做的所以在網上找了些代碼實現了JS搖一搖功能,

具體內容不詳解,直接上碼

HTML代碼

<audio id="musicBox" src=""></audio>

JS代碼

init();
var SHAKE_THRESHOLD = 3000;
var last_update = 0;
var x = y = z = last_x = last_y = last_z = 0;
function init() {
   if (window.DeviceMotionEvent) {
       window.addEventListener(&#39;devicemotion&#39;, deviceMotionHandler, false);
   } else {
       alert(&#39;not support mobile event&#39;);
   }
}
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;
       if (speed > SHAKE_THRESHOLD) {
           alert("感觉到摇动,我要发射了");
           var media = document.getElementById("musicBox"); //获取音频控件
           media.setAttribute("src", "imgy/shake_sound.mp3");
           media.load(); //加载音频
           media.play(); //播放音频 
       }
       last_x = x;
       last_y = y;
       last_z = z;
   }
}


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:js刮獎處理下一篇:js刮獎處理