搖一搖找人、搖一搖抽獎、搖一搖看新聞——這個在 Native App 裡已經近乎標配的功能,其實在網頁上也能做。HTML5 的 DeviceOrientation 把底層的方向與運動感測器做了高階封裝,透過 DOM 事件就能讀到手機的姿態與加速度。
deviceOrientation:封裝方向感測器,能取得手機靜止時的方向資料,例如機身傾角、方位角與朝向。
deviceMotion:封裝運動感測器,能取得手機運動時的加速度與旋轉速率。重力感應球、電子指南針、水平儀,都是靠這兩個事件做出來的。
而 DeviceMotionEvent 回傳的加速度資料分成三個軸:
由於部分裝置沒有硬體能排除重力的影響,這個事件會提供兩個屬性:accelerationIncludingGravity(含重力的加速度)與 acceleration(已排除重力)。做搖一搖時,通常抓前者就夠用了。
這是整個功能最關鍵、也最容易被忽略的一步。單純偵測「加速度超過某個值」會誤判得很嚴重,因為走路、搭車、手機放在口袋裡都會產生加速度變化。可以從三個角度來收斂條件:
實作上的折衷做法是:間隔一段固定時間取樣,計算三軸加速度變化量的絕對值總和並換算成「速度」,再設定一個閾值來觸發。閾值越高越不容易誤觸,但也越難搖動成功,需要依實機測試調整。
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// 搖動閾值,需依實機測試調整
var SHAKE_THRESHOLD = 3000;
var last_update = 0;
var x, y, z, last_x, last_y, last_z;
var count = 0;
function init() {
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', deviceMotionHandler, false);
$("#yaoyiyaoyes").show();
} else {
$("#yaoyiyaono").show();
}
}
function deviceMotionHandler(eventData) {
var acceleration = eventData.accelerationIncludingGravity;
if (!acceleration) return;
var curTime = new Date().getTime();
var diffTime = curTime - last_update;
// 固定時間窗取樣,避免過於頻繁
if (diffTime > 100) {
last_update = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
// 三軸變化量總和換算為速度
var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
if (speed > SHAKE_THRESHOLD) {
count++;
$("#yaoyiyaoyes").hide();
$("#yaoyiyaoresult").show();
$("#yaoyiyaoresult").html("搖出了第 " + count + " 次!");
}
last_x = x;
last_y = y;
last_z = z;
}
}
$(document).ready(function () {
init();
});
</script>
<div id="yaoyiyaono" style="font-size:20px;margin:10px;line-height:35px;display:none;">
目前 this device 不支援搖一搖:
<br>1. 若您使用電腦瀏覽器,請改用智慧型手機開啟;
<br>2. 若您使用 Android 機型,部分系統內建瀏覽器不支援此 API,建議改用 Chrome 或 UCWeb;
<br>3. 若以上皆非,那真的該換手機了。
</div>
<div id="yaoyiyaoyes" style="font-size:20px;margin:10px;line-height:50px;display:none;">
來搖一下吧!
</div>
<div id="yaoyiyaoresult" style="font-size:20px;margin:10px;line-height:50px;display:none;"></div>
必須在 HTTPS 下才能運作。現代瀏覽器已把加速度、方向這類感測器 API 列為需要安全內容的敏感功能,HTTP 頁面完全不會觸發。這是近幾年最常見的失敗原因。
iOS 13 之後需要主動請求授權。必須在使用者點擊手勢的同步流程中呼叫:
if (typeof DeviceMotionEvent.requestPermission === 'function') {
DeviceMotionEvent.requestPermission()
.then(state => { if (state === 'granted') { /* 開始監聽 */ } })
.catch(console.error);
}
少了這一步,iPhone 上永遠讀不到資料。
記得在離開時移除監聽。devicemotion 的觸發頻率可達每秒 60 次以上,若頁面切換後仍持續綁定,會明顯耗電。用 window.removeEventListener('devicemotion', deviceMotionHandler) 在 visibilitychange 或元件卸载時清掉。
把 SHAKE_THRESHOLD 與取樣間隔調順之後,再換上真正的業務邏輯(抽獎、切歌、配對),這就是一個完整可用的搖一搖了。