跳至主要內容
版本:v8

@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) {
// Handle error
return;
}

// Once the user approves, can start listening:
accelHandler = await Motion.addListener('accel', event => {
console.log('Device motion event:', event);
});
});

// Stop the acceleration listener
const stopAcceleration = () => {
if (accelHandler) {
accelHandler.remove();
}
};

// Remove all listeners
const removeListeners = () => {
Motion.removeAllListeners();
};

請參閱 DeviceMotionEvent API 以了解 'accel' 事件中提供的資料。

API

addListener('accel', ...)

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

為加速計資料新增監聽器

參數類型
eventName'accel'
listenerFuncAccelListener

回傳: Promise<PluginListenerHandle>

1.0.0


addListener('orientation', ...)

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

為裝置方向變更(羅盤方位等)新增監聽器

參數類型
eventName'orientation'
listenerFuncOrientationListener

回傳: Promise<PluginListenerHandle>

1.0.0


removeAllListeners()

removeAllListeners() => Promise<void>

移除附加到此外掛程式的所有監聽器。

1.0.0


介面

PluginListenerHandle

屬性類型
remove() => Promise<void>

AccelListenerEvent

屬性類型描述
acceleration加速度一個物件,提供裝置在 X、Y 和 Z 三個軸上的加速度。 加速度以 m/s 表示。1.0.0
accelerationIncludingGravity加速度一個物件,提供裝置在 X、Y 和 Z 三個軸上的加速度,並包含重力影響。 加速度以 m/s 表示。1.0.0
rotationRate旋轉速率一個物件,提供裝置在 alpha、beta 和 gamma 三個方向軸上的方向變更速率。 旋轉速率以度/秒表示。1.0.0
interval數字一個數字,代表從裝置取得資料的時間間隔(以毫秒為單位)。1.0.0

加速度

屬性類型描述
x數字沿 X 軸的加速度量。1.0.0
y數字沿 Y 軸的加速度量。1.0.0
z數字沿 Z 軸的加速度量。1.0.0

旋轉速率

屬性類型描述
alpha數字繞 Z 軸旋轉的量,以度/秒為單位。1.0.0
beta數字繞 X 軸旋轉的量,以度/秒為單位。1.0.0
gamma數字繞 Y 軸旋轉的量,以度/秒為單位。1.0.0

類型別名

AccelListener

(event: AccelListenerEvent): void

OrientationListener

(event: RotationRate): void

OrientationListenerEvent

旋轉速率