跳到主要内容
版本:v3

@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();
};

请参阅 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


接口

PluginListenerHandle

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

AccelListenerEvent

属性类型描述
acceleration
Acceleration
一个对象,表示设备在 X、Y 和 Z 三个轴上的加速度。Acceleration 的单位是 m/s1.0.0
accelerationIncludingGravity
Acceleration
一个对象,表示设备在 X、Y 和 Z 三个轴上包含重力影响的加速度。Acceleration 的单位是 m/s1.0.0
rotationRate
RotationRate
一个对象,表示设备在 alpha、beta 和 gamma 三个方向轴上的方向变化率。旋转速率的单位是度每秒。1.0.0
intervalnumber一个数字,表示从设备获取数据的间隔时间,单位为毫秒。1.0.0

Acceleration

属性类型描述
xnumber沿 X 轴方向的加速度量。1.0.0
ynumber沿 Y 轴方向的加速度量。1.0.0
znumber沿 Z 轴方向的加速度量。1.0.0

RotationRate

属性类型描述
alphanumber绕 Z 轴的旋转量,单位为度每秒。1.0.0
betanumber绕 X 轴的旋转量,单位为度每秒。1.0.0
gammanumber绕 Y 轴的旋转量,单位为度每秒。1.0.0

类型别名

AccelListener

(event: AccelListenerEvent): void

OrientationListener

(event: RotationRate): void

OrientationListenerEvent

RotationRate