移动Web实现摇一摇

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
var lastTime = 0,
x,
y,
z,
lastX,
lastY,
lastZ;
function deviceMotionHandler(eventData) {
var acceleration = eventData.accelerationIncludingGravity,
curTime = new Date().getTime(),
diffTime,
speed;
// 时间
if ((curTime - lastTime)> 100) {
diffTime = curTime - lastUpdate;
lastTime = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
log([x,y,z].join(', '));
speed = Math.abs(x +y + z - lastX - lastY - lastZ) / diffTime * 10000;
if (speed > 400) {
log("摇啊摇!");
}
lastX = x;
lastY = y;
lastZ = z;
}
}
function log(text) {
var console = document.getElementById('console'),
html = console.innerHTML,
msg = '<div class="log">'+ text +'</div>';
console.innerHTML = msg + html;
}
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', deviceMotionHandler, false);
}