实验中的功能,兼容性有效性看实际情况。这里用来获取南北方向。
注意:以下内容都在我的安卓设备测试通过,其它设备请自测。
参考:MDN Web Docs
// DeviceOrientationEventListener.js
/**
* @Author LuoYang
* @Email toluoyang@qq.com
* @Date 2022/3/1 10:18 上午
* @Description 方向事件监听
* @声明:本代码不建议”996或类似不遵守劳动法的组织及其成员”学习使用
*/
let ua = undefined;
// 偏北旋转角度
let rotate = undefined;
let gamma = 0;
/*添加方向事件监听*/
export function addDeviceOrientationEvent() {
if (window.DeviceOrientationEvent) {
ua = navigator.userAgent.toLowerCase();
if (/android/.test(ua)) {
window.addEventListener(
"deviceorientationabsolute",
deviceOrientationHandler,
false
);
} else {
//IOS13+ 授权流程
window.DeviceOrientationEvent.requestPermission().then((state) => {
switch (state) {
case "granted":
window.addEventListener(
"deviceorientation",
deviceOrientationHandler,
false
);
break;
case "denied":
alert("您拒绝了使用陀螺仪");
break;
case "prompt":
alert("获取陀螺仪权限失败");
break;
}
});
}
} else {
alert("您的浏览器不支持陀螺仪");
}
}
function deviceOrientationHandler(event) {
if (/android/.test(ua)) {
rotate = event.alpha;
} else {
rotate = event.webkitCompassHeading;
}
gamma = event.gamma;
}
// 移除方向事件监听
export function removeDeviceOrientationEvent() {
if (/android/.test(ua)) {
window.removeEventListener(
"deviceorientationabsolute",
deviceOrientationHandler
);
} else {
window.removeEventListener("deviceorientation", deviceOrientationHandler);
}
}
// 获取偏北角
export function getRotate() {
return rotate;
}
// 获取摄像头朝向角
export function getCamera() {
return rotate + gamma;
}
// 获取方向名
export function getHeadName(rotate) {
let headName = "北";
let headNum = Math.round(Math.round(rotate / 45) + 7) % 8;
switch (headNum) {
case 0:
headName = "西北";
break;
case 1:
headName = "西";
break;
case 2:
headName = "西南";
break;
case 3:
headName = "南";
break;
case 4:
headName = "东南";
break;
case 5:
headName = "东";
break;
case 6:
headName = "东北";
break;
case 7:
headName = "北";
}
return headName;
}