let ua = undefined;
let rotate = undefined;
export function addDeviceOrientationEvent() {
if (window.DeviceOrientationEvent) {
ua = navigator.userAgent.toLowerCase();
if (/android/.test(ua)) {
window.addEventListener(
"deviceorientationabsolute",
deviceOrientationHandler,
false
);
} else {
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("您的浏览器不支持DeviceOrientation");
}
}
function deviceOrientationHandler(event) {
if (/android/.test(ua)) {
rotate = event.alpha;
} else {
rotate = event.webkitCompassHeading;
}
console.log(rotate);
}
export function removeDeviceOrientationEvent() {
if (/android/.test(ua)) {
window.removeEventListener(
"deviceorientationabsolute",
deviceOrientationHandler
);
} else {
window.removeEventListener("deviceorientation", deviceOrientationHandler);
}
}
export function getRotate() {
return rotate;
}