@capacitor/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 | |
返回:
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
接口
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 |
类型别名
AccelListener
(event: AccelListenerEvent): void
OrientationListener
(event: RotationRate): void
OrientationListenerEvent
RotationRate