useOrientation
监控设备的方向和运动状态,获取旋转角度和加速度数据。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.vue.ref | <T>(value: T) => Ref<T> | Vue ref 函数 |
deps.vue.onMounted | (fn: () => void) => void | Vue onMounted 钩子 |
deps.vue.onUnmounted | (fn: () => void) => void | Vue onUnmounted 钩子 |
deps.window | WindowWithOrientation | Window 对象 |
deps.isMobile | boolean | 是否为移动设备(使用 isMobile() 函数检测) |
环境要求
浏览器 API: DeviceOrientation API, DeviceMotion API
通常需要在移动设备上测试,部分浏览器需要 HTTPS 环境。
函数签名
typescript
function useOrientation(
deps: UseOrientationDeps
): UseOrientationReturn
interface UseOrientationDeps {
vue: VueCompositionAPI
window: WindowWithOrientation
isMobile: boolean
}
interface UseOrientationReturn {
isSupported: Ref<boolean>
isAbsolute: Ref<boolean>
alpha: Ref<number | null>
beta: Ref<number | null>
gamma: Ref<number | null>
accelerationX: Ref<number | null>
accelerationY: Ref<number | null>
accelerationZ: Ref<number | null>
error: Ref<string | null>
}参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
deps | UseOrientationDeps | 是 | 依赖注入对象 |
返回值
| 属性 | 类型 | 说明 |
|---|---|---|
isSupported | Ref<boolean> | 是否支持方向传感器 |
isAbsolute | Ref<boolean> | 是否为绝对定向(相对地球坐标系) |
alpha | Ref<number | null> | Z轴旋转角度 (0-360°) |
beta | Ref<number | null> | X轴旋转角度 (-180° to 180°) |
gamma | Ref<number | null> | Y轴旋转角度 (-90° to 90°) |
accelerationX | Ref<number | null> | X轴加速度 (m/s²) |
accelerationY | Ref<number | null> | Y轴加速度 (m/s²) |
accelerationZ | Ref<number | null> | Z轴加速度 (m/s²) |
error | Ref<string | null> | 错误信息 |
方向角度说明
Alpha(Z轴旋转)
- 范围:0° - 360°
- 方向:绕垂直于屏幕的轴旋转(指南针方向)
- 0°:设备顶部指向北方
Beta(X轴旋转)
- 范围:-180° - 180°
- 方向:绕水平轴旋转(前后倾斜)
- 0°:设备水平放置
- 正值:设备顶部向后倾斜
- 负值:设备顶部向前倾斜
Gamma(Y轴旋转)
- 范围:-90° - 90°
- 方向:绕垂直轴旋转(左右倾斜)
- 0°:设备水平放置
- 正值:设备向右倾斜
- 负值:设备向左倾斜
工作原理
- 检查是否为移动设备(通过
isMobile参数) - 只有移动设备才支持方向传感器(桌面设备没有陀螺仪)
- 在组件挂载时添加
deviceorientation和devicemotion事件监听 - 实时获取设备的旋转角度(alpha、beta、gamma)
- 实时获取设备的加速度数据
- 所有数据通过响应式状态更新
- 组件卸载时移除事件监听器
注意:方向传感器仅在移动设备(手机/平板)上可用,桌面浏览器通常不支持此功能。
可用于:
- 游戏控制(重力感应)
- AR/VR 应用
- 指南针应用
- 水平仪工具
- 摇一摇功能
- 手势识别