Skip to content

Instantly share code, notes, and snippets.

@maisui99
Created May 20, 2014 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maisui99/ce0ff7d8d3de1efe7413 to your computer and use it in GitHub Desktop.
Save maisui99/ce0ff7d8d3de1efe7413 to your computer and use it in GitHub Desktop.
简单的摇一摇实现
if (typeof window.DeviceMotionEvent != 'undefined') {
// Shake sensitivity (a lower number is more)
var sensitivity = 20;
// Position variables
var x1 = 0, y1 = 0, z1 = 0, x2 = 0, y2 = 0, z2 = 0;
// Listen to motion events and update the position
window.addEventListener('devicemotion', function (e) {
x1 = e.accelerationIncludingGravity.x;
y1 = e.accelerationIncludingGravity.y;
z1 = e.accelerationIncludingGravity.z;
}, false);
// Periodically check the position and fire
// if the change is greater than the sensitivity
var timer = setInterval(function () {
var change = Math.abs(x1 - x2 + y1 - y2 + z1 - z2);
if (change > sensitivity) {
callback();
clearInterval(timer);
}
// Update new position
x2 = x1;
y2 = y1;
z2 = z1;
}, 150);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment