方向事件deviceorientation
该事件实在设备方向发生变化时触发, 使用方法如下;
window.addEventListener('deviceorientation', orientationHandler, true);
回调函数orientationHandler会接收到一个DeviceOrientationEvent类型参数, 包含以下信息.
属性名 | 说明 |
---|---|
absolute | 如果方向数据跟地球坐标系和设备坐标系有差异, 则为true |
alpha | 设备在alpha方向上旋转的角度, 范围为0-360 |
beta | 设备在Beta方向上旋转的角度, 范围为-180-180 |
gamma | 设备在Gamma方向上旋转的角度, 范围为-90-90 |
移动事件devicemotion
该事件实在设备位置发生变化时触发
window.addEventListener('devicemotion', motionHandler, false);
该回调函数会接受DeviceMotionEvent类型参数, 包含以下信息.
属性名 | 说明 |
---|---|
acceleration | 设备在X,Y,Z三个轴的方向上移动的距离, 以抵消重力加速度 |
accelerationIncludingGravity | 设备在X,Y,Z三个轴方向移动的距离, 包含重力加速度 |
rotationRate | 设备在Alpha, Beta, Gamma三个方向旋转的角度 |
interval | 从设备获取数据的频率, 单位是毫秒 |
代码部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>摇一摇</title>
</head>
<body>
<div>
摇一摇
</div>
<script>
const SHAKE_SPEED = 300;
let lastTime = 0;//上次变化的时间
let x = y = z = lastX = lastY = lastZ = 0;//位置变量初始化
function motionHandler(event) {
let acceleration = event.accelerationIncludingGravity;
let curTime = Date.now();//取得当前时间
if ((curTime - lastTime) > 120) {
let diffTime = curTime - lastTime;
lastTime = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
//计算摇动速度
let speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 1000;
if (speed > SHAKE_SPEED) {
alert("你摇动了手机");
}
lastX = x;
lastY = y;
lastZ = z;
}
}
if(window.DeviceMotionEvent) {
window.addEventListener('devicemotion', motionHandler, false);
} else {
alert("你的设备不支持位置感应");
}
</script>
</body>
</html>