透過 DeviceMotionEvent,網頁可以讀取裝置的加速度變化。當使用者搖動手機,若 x 或 y 軸變化超過門檻,就觸發換色。
var color = new Array('red', 'blue', 'yellow', 'green', '#00f', '#0ff');
if (window.DeviceMotionEvent) {
var speed = 25;
var x = y = lastX = lastY = 0;
window.addEventListener('devicemotion', function(event) {
var acceleration = event.accelerationIncludingGravity;
x = acceleration.x;
y = acceleration.y;
if (Math.abs(x - lastX) > speed || Math.abs(y - lastY) > speed) {
document.body.style.backgroundColor = color[Math.round(Math.random() * 10) % 6];
}
lastX = x;
lastY = y;
}, false);
}
若要更穩定,可加入冷卻時間、平均值濾波或 debounce,避免一次搖動觸發多次。