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 端中使用浏览器调试

 

猜你喜欢

转载自www.cnblogs.com/sanyekui/p/12725621.html