DeviceOrientation API 提供欧拉角(α/β/γ),适用于罗盘等场景;DeviceMotion API 的 rotationRate 提供高频率原始陀螺仪角速度(°/s),适合游戏等精细追踪,均需用户交互触发并处理权限、兼容性及滤波降噪。
JavaScript 通过 DeviceOrientation API 和 DeviceMotion API 获取设备方向与运动数据,其中陀螺仪(角速度)信息主要由 deviceorientation 事件提供,而更底层、高频率的原始陀螺仪数据则需使用 devicemotion 事件中的 rotationRate 字段。
该事件提供基于地理坐标的设备朝向:α(方位角,绕 z 轴)、β(俯仰角,绕 x 轴)、γ(横滚角,绕 y 轴),单位为度。适用于罗盘、简单体感交互等场景。
function handleOrientation(event) {
console.log(`α: ${event.alpha}, β: ${event.beta}, γ: ${event.gamma}`);
}
document.addEventListener('click', () => {
window.addEventListener('deviceorientation', handleOrientation);
});
event.absolute 或降级处理devicemotion 事件的 rotationRate 属性直接暴露陀螺仪的角速度(单位:°/s),包含 alpha(绕 z)、beta(绕 x)、gamma(绕 y)三个分量,采样率更高、延迟更低,适合游戏或精细姿态追踪。
function handleMotion(event) {
const r = event.rotationRate;
if (r) {
console.log(`绕x轴旋转速度: ${r.beta} °/s`);
}
}
button.addEventListener('click', () => {
window.addEventListener('devicemotion', handleMotion, { passive: true });
});
中添加:
从 Chrome 88+ 和 Safari 15.4+ 开始,访问运动传感器需显式请求权限,否则事件不会触发或返回空值。
if (typeof DeviceMotionEvent.requestPermission === 'function') {
document.addEventListener('click', async () => {
try {
await DeviceMotionEvent.requestPermission();
window.addEventListener('devicemotion', handleMotion);
} catch (e) {
console.error('权限被拒绝:', e);
}
});
}
'ontouchstart' in window 粗略判断是否为移动设备原始陀螺仪数据存在漂移和高频噪声,直接使用易导致抖动。推荐轻量级滤波:
filtered = filtered * 0.8 + current * 0.2