forked from ksky521/nodeppt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shake.js
44 lines (35 loc) · 983 Bytes
/
shake.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
(function(window, document) {
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', deviceMotionHandler, false);
}
var SHAKE_THRESHOLD = 1500;
var lastUpdate = 0;
var x, y, z, last_x, last_y, last_z;
var shakeEvent = [];
function deviceMotionHandler(eventData) {
// Grab the acceleration including gravity from the results
var acceleration = eventData.accelerationIncludingGravity;
var curTime = +new Date();
if ((curTime - lastUpdate) > 100) {
var diffTime = (curTime - lastUpdate);
lastUpdate = 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) {
shakeEvent.forEach(function(v) {
if (typeof v === 'function') {
v();
}
});
}
last_x = x;
last_y = y;
last_z = z;
}
}
window.addShakeEvent = function(fn) {
shakeEvent.push(fn);
}
}(window, document));