H5 陀螺仪(DeviceOrientationEvent)

H5 陀螺仪(DeviceOrientationEvent)


h5陀螺仪,ios需要特殊处理,ios13以上调用陀螺仪需要申请权限(需要用户手动授权,不能默认授权,并且ios真机测试时需要h使用https)
话不多说 直接上代码

  1. Alpha:以Z轴为轴的旋转为alpha。其范围为0到360度,当前指向表示为z。
  2. Beta:以X轴为轴的旋转为beta。其范围为-180到180度,当前指向表示为x。
  3. Gamma:以Y轴为轴的旋转为gamma。其范围为-90到90度,当前指向表示为y。

🤫 嘘~偷的图

var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

//判断是ios还是安卓
if(isiOS){
	if(window.DeviceOrientationEvent.requestPermission){
		window.DeviceOrientationEvent.requestPermission().then(state => {
			if(state === "granted"){//允许
				console.log("用户允许",state)
				monitor();
			}else if(state === "denied"){//拒绝
				alert('您已拒绝倾斜手机,请退出微信重新进入授权~');
				console.log("用户拒绝",state)
			}else if(state === "prompt"){
				console.log("用户干了啥",state);
				alert('遇到未知错误,请退出微信重新进入~')
			}
		})
	}else{
		monitor();
	}		
}else if(isAndroid){
	monitor();
}

// 陀螺仪旋转后事件处理
function monitor() {
	if(window.DeviceMotionEvent){
		window.addEventListener("deviceorientation", function(e) {
			console.log(e.alpha,e.beta,e.gamma);
			// 做你想做的操作
		}
	}else{
		alert('您的手机不支持陀螺仪哦~')
	}
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值