H5 - 獲取手機陀螺儀


直接上代碼:

// 獲取手機陀螺儀
var updateGravity = function(event) { console.log("alpha:",event.alpha); // X
    console.log("beta:",event.beta); // Y
    console.log("gamma:",event.gamma); // Z
 }; // 監聽 window 的 deviceorientation 事件 
window.addEventListener('deviceorientation', updateGravity, false);

ios系統需要 https:// 協議才能獲取。

 

目前ios最新版本 13以上需要申請用戶權限:window.DeviceOrientationEvent.requestPermission();

 

$('.Gravity').on('click',function(){ // ios 提示授權, 返回的是一個 promise
 window.DeviceOrientationEvent.requestPermission() .then(state => { if(state === "granted"){//允許
            alert("允許使用陀螺儀:",state) }else if(state === "denied"){//拒絕
            alert("拒絕使用陀螺儀:",state) }else if(state === "prompt"){ alert("用戶進行其他操作:",state) } }) })     

 

目前發現需要使用 click / touched 等點擊事件才能去觸發使用,需要注意,一旦點擊了確定或者拒絕,系統就會保留授權權限,不會再彈出提示框,需要重新授權就要完全退出app等程序再次進入。

 在手機端上才能測試使用,在PC端瀏覽器中會報錯!

 

在PC 端中使用瀏覽器調試

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM