html5實現搖一搖

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   java   ar   資料   2014   

利用html5實作類別似的手機搖一搖功能,並播放音樂。

1、  deviceOrientation:封裝了方向感應器資料的事件,能夠擷取手機精巧狀態下的方向資料,比如手機所處角度、方位、朝向等。

2、  deviceMotion:封裝了動作感應器資料的事件,能夠擷取手機運動狀態下的運動加速度等資料。


<!DOCTYPE html><html lang="cn"><head>    <meta charset="utf-8" />    <meta name="viewport" content="width=device-width, initial-scale=1.0" />    <title>搖一搖功能</title>    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>    <script type="text/javascript">// 首先在頁面上要監聽運動感測事件 function init(){// 推斷行動瀏覽器支援運動感測事件if (window.DeviceMotionEvent) { window.addEventListener(‘devicemotion‘,deviceMotionHandler, false);  }else{alert(‘不支援移動事件‘);}}var SHAKE_THRESHOLD = 3000;   // 首先,定義一個搖動的閥值 var last_update = 0;  // 定義一個變數儲存上次更新的時間  var x=y=z=last_x=last_y=last_z=0;  // 緊接著定義x、y、z記錄三個軸的資料以及上一次出發的時間var count = 0;function deviceMotionHandler(eventData) {    var acceleration =eventData.accelerationIncludingGravity;  // 擷取目前時間var curTime = new Date().getTime(); var diffTime = curTime -last_update;// 固定時間段if (diffTime > 100) {  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) {   // TODO:在此處能夠實現搖一搖之後所要進行的資料邏輯操作count++;alert("搖動了");     alert("搖你妹!第" + count + "個了!"); }    last_x = x;    last_y = y;    last_z = z;    }    }    </script></head><body onload="init()"><p>用力搖一搖你手機</p><audio style="display:hiden" id="musicBox" preload="metadata" controls src="http://211.148.5.228:8002/Pages/test/Kalimba.mp3" autoplay="false"></audio></body></html>

html5實現搖一搖

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.