0
点赞
收藏
分享

微信扫一扫

JS获取移动设备方向

// DeviceOrientationEventListener.js
/**
 * @Author LuoYang
 * @Email toluoyang@qq.com
 * @Date 2022/3/1 10:18 上午
 * @Description 方向事件监听
 */

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 {
      //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("您的浏览器不支持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;
}
举报

相关推荐

0 条评论