萬盛學電腦網

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

HTML5 DeviceMotion 實作手機搖一搖功能完整教學

利用 HTML5 DeviceOrientation API 中的 `devicemotion` 事件,即可在網頁實現「搖一搖」互動。本文從原理到完整程式碼逐步解析。

核心概念

  • deviceorientation:靜態方向資料(alpha, beta, gamma)
  • devicemotion:動態運動資料,包含加速度(含重力/不含重力)與旋轉率

搖一搖偵測使用 devicemotion 的 accelerationIncludingGravity(含重力加速度),因部分裝置無法分離重力。

加速度資料結構

event.accelerationIncludingGravity.x // 左右傾斜
event.accelerationIncludingGravity.y // 前後傾斜
event.accelerationIncludingGravity.z // 垂直螢幕

偵測邏輯:計算速度變化率

  1. 設定閾值 SHAKE_THRESHOLD(經驗值約 3000)
  2. 記錄上次更新時間與上一次的 x, y, z
  3. 每 100ms 計算一次速度變化量
const SHAKE_THRESHOLD = 3000;
let lastUpdate = 0;
let lastX = 0, lastY = 0, lastZ = 0;

function deviceMotionHandler(event) {
  const acc = event.accelerationIncludingGravity;
  const now = Date.now();
  const diffTime = now - lastUpdate;

  if (diffTime > 100) {
    lastUpdate = now;
    const x = acc.x, y = acc.y, z = acc.z;
    // 速度公式:三軸變化量總和 / 時間差 * 放大係數
    const speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000;

    if (speed > SHAKE_THRESHOLD) {
      triggerShakeAction();
    }
    lastX = x; lastY = y; lastZ = z;
  }
}

function triggerShakeAction() {
  console.log('搖一搖觸發!');
  // 這裡執行業務邏輯:抽獎、換頁、播放音效等
}

if (window.DeviceMotionEvent) {
  window.addEventListener('devicemotion', deviceMotionHandler, false);
} else {
  console.warn('裝置不支援 DeviceMotionEvent');
}

完整 HTML 範例(含 UI 回饋)

<div id="status">搖動手機試試</div>
<script>
const SHAKE_THRESHOLD = 3000;
let lastUpdate = 0, lastX=0, lastY=0, lastZ=0, count=0;

function deviceMotionHandler(e) {
  const a = e.accelerationIncludingGravity;
  const now = Date.now();
  if (now - lastUpdate > 100) {
    const diff = now - lastUpdate;
    lastUpdate = now;
    const speed = Math.abs(a.x + a.y + a.z - lastX - lastY - lastZ) / diff * 10000;
    if (speed > SHAKE_THRESHOLD) {
      count++;
      document.getElementById('status').textContent = `搖了 ${count} 次!`;
    }
    lastX = a.x; lastY = a.y; lastZ = a.z;
  }
}

if (window.DeviceMotionEvent) {
  window.addEventListener('devicemotion', deviceMotionHandler);
} else {
  document.getElementById('status').textContent = '不支援搖一搖';
}
</script>

實務注意事項

  • HTTPS 環境下才能存取感測器(本地 localhost 除外)。
  • iOS 13+ 需使用者透過按鈕點擊請求權限:DeviceMotionEvent.requestPermission()。
  • 閾值需依實測調整,避免走路、車輛震動誤觸發。
  • 搖一搖後建議給予視覺/聽覺回饋,提升體驗。

掌握這套邏輯,即可為行銷活動、遊戲、社交應用快速加入搖一搖互動。

copyright © 萬盛學電腦網 all rights reserved