@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('Device motion event:', event);
});
});
// 停止加速度监听器
const stopAcceleration = () => {
if (accelHandler) {
accelHandler.remove();
}
};
// 删除所有监听器
const removeListeners = () => {
Motion.removeAllListeners();
};
请参阅
DeviceMotionEvent
API 以了解 'accel' 事件中提供的数据。
API
addListener('accel', ...)
addListener(eventName: 'accel', listenerFunc: AccelListener) => Promise<PluginListenerHandle>
添加加速度计数据的监听器
| Param | Type |
|---|---|
eventName | 'accel' |
listenerFunc | |
Returns:
Promise<PluginListenerHandle>
Since: 1.0.0
addListener('orientation', ...)
addListener(eventName: 'orientation', listenerFunc: OrientationListener) => Promise<PluginListenerHandle>
添加设备方向更改的监听器(指南针标题等)
| Param | Type |
|---|---|
eventName | 'orientation' |
listenerFunc | |
Returns:
Promise<PluginListenerHandle>
Since: 1.0.0
removeAllListeners()
removeAllListeners() => Promise<void>
删除附加到此插件的所有监听器。
Since: 1.0.0
Interfaces
PluginListenerHandle
| Prop | Type |
|---|---|
remove | () => Promise<void> |
AccelListenerEvent
| Prop | Type | Description | Since |
|---|---|---|---|
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
| Prop | Type | Description | Since |
|---|---|---|---|
x | number | 沿 X 轴的加速度量。 | 1.0.0 |
y | number | 沿 Y 轴的加速度量。 | 1.0.0 |
z | number | 沿 Z 轴的加速度量。 | 1.0.0 |
RotationRate
| Prop | Type | Description | Since |
|---|---|---|---|
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