forked from ccforward/cc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshake.js
96 lines (75 loc) · 2.7 KB
/
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
(function (window, document) {
// @TODO
function Shake() {
this.hasDeviceMotion = 'ondevicemotion' in window;
//阈值
this.threshold = 15;
this.lastTime = new Date();
//计算每次变化值
this.lastX = null;
this.lastY = null;
this.lastZ = null;
//自定义事件
if (typeof document.CustomEvent === "function") {
this.event = new document.CustomEvent('shake', {
bubbles: true,
cancelable: true
});
} else if (typeof document.createEvent === "function") {
this.event = document.createEvent('Event');
this.event.initEvent('shake', true, true);
} else {
return false;
}
}
Shake.prototype.reset = function () {
this.lastTime = new Date();
this.lastX = null;
this.lastY = null;
this.lastZ = null;
};
Shake.prototype.start = function () {
this.reset();
if (this.hasDeviceMotion) { window.addEventListener('devicemotion', this, false); }
};
Shake.prototype.stop = function () {
if (this.hasDeviceMotion) { window.removeEventListener('devicemotion', this, false); }
this.reset();
};
Shake.prototype.devicemotion = function (e) {
var current = e.accelerationIncludingGravity,
currentTime,
timeDifference,
deltaX = 0,
deltaY = 0,
deltaZ = 0;
if ((this.lastX === null) && (this.lastY === null) && (this.lastZ === null)) {
this.lastX = current.x;
this.lastY = current.y;
this.lastZ = current.z;
return;
}
deltaX = Math.abs(this.lastX - current.x);
deltaY = Math.abs(this.lastY - current.y);
deltaZ = Math.abs(this.lastZ - current.z);
if (((deltaX > this.threshold) && (deltaY > this.threshold)) || ((deltaX > this.threshold) && (deltaZ > this.threshold)) || ((deltaY > this.threshold) && (deltaZ > this.threshold))) {
//计算上次shake后的ms值
currentTime = new Date();
timeDifference = currentTime.getTime() - this.lastTime.getTime();
if (timeDifference > 1000) {
window.dispatchEvent(this.event);
this.lastTime = new Date();
}
}
this.lastX = current.x;
this.lastY = current.y;
this.lastZ = current.z;
};
Shake.prototype.handleEvent = function (e) {
if (typeof (this[e.type]) === 'function') {
return this[e.type](e);
}
};
var myShakeEvent = new Shake();
myShakeEvent && myShakeEvent.start();
}(window, document));