@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' |
listenerFunc | AccelListener |
回傳: Promise<PluginListenerHandle>
自 1.0.0
addListener('orientation', ...)
addListener(eventName: 'orientation', listenerFunc: OrientationListener) => Promise<PluginListenerHandle>
為裝置方向變更(羅盤方位等)新增監聽器
參數 | 類型 |
---|---|
eventName | 'orientation' |
listenerFunc | OrientationListener |
回傳: 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
旋轉速率