利用 HTML5 DeviceOrientation API 中的 `devicemotion` 事件,即可在網頁實現「搖一搖」互動。本文從原理到完整程式碼逐步解析。
搖一搖偵測使用 devicemotion 的 accelerationIncludingGravity(含重力加速度),因部分裝置無法分離重力。
event.accelerationIncludingGravity.x // 左右傾斜
event.accelerationIncludingGravity.y // 前後傾斜
event.accelerationIncludingGravity.z // 垂直螢幕
SHAKE_THRESHOLD(經驗值約 3000)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');
}
<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>
DeviceMotionEvent.requestPermission()。掌握這套邏輯,即可為行銷活動、遊戲、社交應用快速加入搖一搖互動。