萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 搖一搖(Shake)功能最佳實踐:DeviceMotionEvent 封裝、去抖動與動畫鎖機制

利用 DeviceMotionEvent 實現「搖一搖」互動是行動網頁常見需求,但直接使用原始事件易誤觸、重複觸發、動畫衝突。本文從基礎監聽進階到「動畫執行鎖」與「閾值自適應」完整方案,提供可直接投入生產的封裝代碼。

基礎版:原始加速度閾值判斷

if (window.DeviceMotionEvent) {
  const SHAKE_THRESHOLD = 25; // 經驗值,視專案調整
  let lastX = 0, lastY = 0, lastZ = 0;

  window.addEventListener('devicemotion', (e) => {
    const { x, y, z } = e.accelerationIncludingGravity;
    const deltaX = Math.abs(x - lastX);
    const deltaY = Math.abs(y - lastY);
    // const deltaZ = Math.abs(z - lastZ); // Z 軸通常噪聲大,建議不納入

    if (deltaX > SHAKE_THRESHOLD || deltaY > SHAKE_THRESHOLD) {
      triggerShakeAction(); // 你的業務邏輯
    }
    lastX = x; lastY = y; lastZ = z;
  }, { passive: true }); // passive 提升滾動效能
}

進階版:動畫執行鎖防重複觸發

當搖一搖觸發動畫(如抽獎轉盤、骰子滾動)時,必須確保動畫播放完畢前不再響應新的搖動事件。

let isAnimating = false; // 鎖標誌

function triggerShakeAction() {
  if (isAnimating) return; // 動畫中忽略新觸發
  isAnimating = true;

  // 例:jQuery 動畫
  $('.shake-target').animate({ left: 0, opacity: 1 }, 700, () => {
    isAnimating = false; // 動畫結束釋放鎖
  });

  // 或 Promise 版本(現代寫法)
  // await animateShake(); isAnimating = false;
}

if (window.DeviceMotionEvent) {
  const SHAKE_THRESHOLD = 25;
  let lastX = 0, lastY = 0, lastZ = 0;

  window.addEventListener('devicemotion', (e) => {
    const { x, y, z } = e.accelerationIncludingGravity;
    if (Math.abs(x - lastX) > SHAKE_THRESHOLD || Math.abs(y - lastY) > SHAKE_THRESHOLD) {
      triggerShakeAction();
    }
    lastX = x; lastY = y; lastZ = z;
  }, { passive: true });
}

生產級增強建議

  1. 閾值自適應:根據裝置型號(navigator.userAgent)或首次校準階段統計靜止時的噪聲標準差,動態調整 SHAKE_THRESHOLD。
  2. 去抖動時間窗:在觸發後 1-2 秒內忽略後續事件(setTimeout(() => shakeCooldown = false, 1500)),避免手部回彈產生的二次峰值。
  3. 權限與 HTTPS:iOS 13+、Android Chrome 要求 HTTPS 且需使用者手勢(如點擊「開始遊戲」)後才啟用 DeviceMotionEvent,請引導使用者先互動。
  4. 權限請求:iOS 13+ 需呼叫 DeviceMotionEvent.requestPermission(),建議封裝跨平台權限請求函式。
  5. 效能優化:監聽器加 {passive:true} 避免阻塞主執行緒;若無需 Z 軸可不讀取以減少物件建立開銷。
  6. 單元測試:使用 window.dispatchEvent(new DeviceMotionEvent('devicemotion', {accelerationIncludingGravity:{x:30,y:0,z:9.8}})) 模擬搖動進行自動化測試。

完整可復用模組(ES Module 版)

// shake-detector.js
export class ShakeDetector {
  constructor(options = {}) {
    this.threshold = options.threshold || 25;
    this.cooldown = options.cooldown || 1000;
    this.onShake = options.onShake || (() => {});
    this._last = {x:0,y:0,z:0};
    this._cooling = false;
    this._boundHandler = this._handle.bind(this);
  }
  start() {
    if (!window.DeviceMotionEvent) return console.warn('DeviceMotionEvent not supported');
    window.addEventListener('devicemotion', this._boundHandler, {passive:true});
  }
  stop() { window.removeEventListener('devicemotion', this._boundHandler); }
  _handle(e) {
    if (this._cooling) return;
    const {x,y,z} = e.accelerationIncludingGravity;
    const dx = Math.abs(x - this._last.x), dy = Math.abs(y - this._last.y);
    this._last = {x,y,z};
    if (dx > this.threshold || dy > this.threshold) {
      this._cooling = true;
      this.onShake();
      setTimeout(() => this._cooling = false, this.cooldown);
    }
  }
}

// 使用範例
import {ShakeDetector} from './shake-detector.js';
const detector = new ShakeDetector({
  threshold: 20,
  cooldown: 1500,
  onShake: () => { console.log('搖一搖觸發!'); /* 播放動畫、呼叫 API */ }
});
detector.start();
// 頁面卸載時 detector.stop() 釋放資源

採用模組化、可配置、帶生命週期管理的封裝,能讓「搖一搖」功能在複雜專案中穩定、可測試、易維護。

copyright © 萬盛學電腦網 all rights reserved