您好,登錄后才能下訂單哦!
小編給大家分享一下通過html5實現搖一搖的功能的方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
原理:使用DeviceMotion實現,關于DeviceMotion介紹可以查看
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/devicemotion
通過DeviceMotionEvent,可以獲得accelerationIncludingGravity的x,y,z屬性,根據x,y,z屬性的變化來判斷設備是否有搖一搖的事件發生。
accelerationIncludeingGravity說明:
The acceleration of the device. This value includes the effect of gravity, and may be the only value available on devices that don’t have a gyroscope to allow them to properly remove gravity from the data.
代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title> html5使用DeviceMotionEvent實現搖一搖 </title> <style type="text/css"> .center{position:absolute; width:640px; height:480px; left:50%; top:50%; margin-left:-320px; margin-top:-240px; line-height:480px; text-align:center; font-size:100px; } .normal{background:#000000;} .normal .txt{color:#FFFFFF;} .doing{background:#FF0000;} .doing .txt{color:#FFFF00;} </style> </head> <body id="mybody" class="normal"> <p id="txt" class="txt center">請執行搖一搖</p> </body> <script type="text/javascript"> var doing = 0; // 判斷是否在動畫顯示中 var speed = 23; // 定義搖動的速度數值 var lastx = 0; var lasty = 0; var lastz = 0; function handleMotionEvent(event) { var x = event.accelerationIncludingGravity.x; var y = event.accelerationIncludingGravity.y; var z = event.accelerationIncludingGravity.z; if(doing==0){ if(Math.abs(x-lastx)>speed || Math.abs(y-lasty)>speed){ doing = 1; show(); } } lastx = x; lasty = y; lastz = z; } function show(){ document.getElementById('mybody').className = 'doing'; document.getElementById('txt').innerHTML = '執行了搖一搖'; setTimeout(function(){ doing=0; document.getElementById('mybody').className='normal'; document.getElementById('txt').innerHTML = '請執行搖一搖'; },3000); } window.addEventListener("devicemotion", handleMotionEvent, true); </script></html>
看完了這篇文章,相信你對通過html5實現搖一搖的功能的方法有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。