跳到主要内容
版本:v3

@capacitor/motion

Motion API 用于追踪加速度计和设备方向数据(指南针朝向等)

安装

npm install @capacitor/motion
npx cap sync

权限说明

本插件目前基于 Web 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();
};

请参考 DeviceMotionEvent API 文档了解 'accel' 事件返回的数据结构。

API 文档

addListener('accel', ...)

addListener(eventName: 'accel', listenerFunc: AccelListener) => Promise<PluginListenerHandle> & PluginListenerHandle

添加加速度计数据监听器

参数类型
eventName'accel'
listenerFunc
AccelListener

返回值:

Promise<PluginListenerHandle> & PluginListenerHandle

自版本: 1.0.0


addListener('orientation', ...)

addListener(eventName: 'orientation', listenerFunc: OrientationListener) => Promise<PluginListenerHandle> & PluginListenerHandle

添加设备方向变化监听器(指南针朝向等)

参数类型
eventName'orientation'
listenerFunc
OrientationListener

返回值:

Promise<PluginListenerHandle> & PluginListenerHandle

自版本: 1.0.0


removeAllListeners()

removeAllListeners() => Promise<void>

移除本插件所有已附加的监听器。

自版本: 1.0.0


Interfaces

PluginListenerHandle

属性类型
remove() => Promise<void>

AccelListenerEvent

属性类型描述版本
acceleration
Acceleration
表示设备在 X、Y、Z 三轴上的加速度对象。Acceleration 单位为 m/s²1.0.0
accelerationIncludingGravity
Acceleration
表示设备在 X、Y、Z 三轴上包含重力影响的加速度对象。Acceleration 单位为 m/s²1.0.0
rotationRate
RotationRate
表示设备在 alpha、beta、gamma 三个方向轴上旋转角速度的对象。单位为度/秒1.0.0
intervalnumber表示从设备获取数据的间隔时间(毫秒)1.0.0

Acceleration

属性类型描述版本
xnumberX 轴方向的加速度值1.0.0
ynumberY 轴方向的加速度值1.0.0
znumberZ 轴方向的加速度值1.0.0

RotationRate

属性类型描述版本
alphanumber绕 Z 轴的旋转角速度(度/秒)1planet.0.0
betanumber绕 X 轴的旋转角速度(度/秒)1.0.0
gammanumber绕 Y 轴的旋转角速度(度/秒)1.0.0

Type Aliases

AccelListener


  (event: AccelListenerEvent): void

OrientationListener


  (event: RotationRate): void

OrientationListenerEvent


  RotationRate