@capacitor/motion
Motion API 用于追踪加速度计和设备方向(如指南针朝向等)
安装
npm install @capacitor/motion
npx cap sync
权限说明
本插件目前基于 Web API 实现。大多数浏览器需要用户授权才能使用此 API。可以通过用户主动触发的动作(如按钮点击)来请求权限:
import { PluginListenerHandle } from '@capacitor/core';
import { Motion } from '@capacitor/motion';
let accelHandler: PluginListenerHandle;
myButton.addEventListener('click', async () => {
try {
await DeviceMotionEvent.requestPermission();
} catch (e) {
// 处理错误
return;
}
// 用户授权后可以开始监听:
accelHandler = await Motion.addListener('accel', (event) => {
console.log('设备运动事件:', event);
});
});
// 停止加速度监听
const stopAcceleration = () => {
if (accelHandler) {
accelHandler.remove();
}
};
// 移除所有监听器
const removeListeners = () => {
Motion.removeAllListeners();
};
关于 'accel' 事件提供的数据结构,请参考
DeviceMotionEvent
API 文档。
API 参考
addListener('accel', ...)
addListener(eventName: 'accel', listenerFunc: AccelListener) => Promise<PluginListenerHandle> & PluginListenerHandle
添加加速度计数据监听器
参数 | 类型 |
---|---|
eventName | 'accel' |
listenerFunc |
|
返回值:
Promise<PluginListenerHandle> & PluginListenerHandle
自版本: 1.0.0
addListener('orientation', ...)
addListener(eventName: 'orientation', listenerFunc: OrientationListener) => Promise<PluginListenerHandle> & PluginListenerHandle
添加设备方向变化监听器(指南针朝向等)
参数 | 类型 |
---|---|
eventName | 'orientation' |
listenerFunc |
|
返回值:
Promise<PluginListenerHandle> & PluginListenerHandle
自版本: 1.0.0
removeAllListeners()
removeAllListeners() => Promise<void>
移除该插件附加的所有监听器
自版本: 1.0.0
Interfaces
PluginListenerHandle
属性 | 类型 |
---|---|
remove | () => Promise<void> |
AccelListenerEvent
属性 | 类型 | 说明 | 版本 |
---|---|---|---|
acceleration |
| 包含设备在 X/Y/Z 三轴上加速度的对象。Acceleration 单位为 m/s | 1.0.0 |
accelerationIncludingGravity |
| 包含设备在 X/Y/Z 三轴上加速度(含重力影响)的对象。Acceleration 单位为 m/s | 1.0.0 |
rotationRate |
| 包含设备在 alpha/beta/gamma 三轴方向上旋转速率的对象。旋转速率单位为度/秒 | 1.0.0 |
interval | number | 从设备获取数据的间隔时间(毫秒) | 1.0.0 |
Acceleration
属性 | 类型 | 说明 | 版本 |
---|---|---|---|
x | number | X 轴方向的加速度值 | 1.0.0 |
y | number | Y 轴方向的加速度值 | 1.0.0 |
z | number | Z 轴方向的加速度值 | 1.0.0 |
RotationRate
属性 | 类型 | 说明 | 版本 |
---|---|---|---|
alpha | number | 绕 Z 轴旋转的角速度(度/秒) | 1.0.0 |
beta | number | 绕 X 轴旋转的角速度(度/秒) | 1.0.0 |
gamma | number | 绕 Y 轴旋转的角速度(度/秒) | 1.0.0 |
Type Aliases
AccelListener
(event: AccelListenerEvent): void
OrientationListener
(event: RotationRate): void
OrientationListenerEvent
RotationRate