/
accel.html
79 lines (63 loc) · 2.62 KB
/
accel.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Accelerometer Demo</title>
<style>
.indicatorDot {
width: 30px;
height: 30px;
background-color: #ffab56;
border-radius: 50%;
position: fixed;
}
</style>
<script>
var px = 50; // Position x and y
var py = 50;
var vx = 0.0; // Velocity x and y
var vy = 0.0;
var updateRate = 1 / 60; // Sensor refresh rate
function getAccel() {
DeviceMotionEvent.requestPermission().then(response => {
if (response == 'granted') {
// Add a listener to get smartphone orientation
// in the alpha-beta-gamma axes (units in degrees)
window.addEventListener('deviceorientation', (event) => {
// Expose each orientation angle in a more readable way
rotation_degrees = event.alpha;
frontToBack_degrees = event.beta;
leftToRight_degrees = event.gamma;
document.getElementById("demo").innerHTML = rotation_degrees;
// Update velocity according to how tilted the phone is
// Since phones are narrower than they are long, double the increase to the x velocity
vx = vx + leftToRight_degrees * updateRate * 2;
vy = vy + frontToBack_degrees * updateRate;
// Update position and clip it to bounds
px = px + vx * .5;
if (px > 98 || px < 0) {
px = Math.max(0, Math.min(98, px)) // Clip px between 0-98
vx = 0;
}
py = py + vy * .5;
if (py > 98 || py < 0) {
py = Math.max(0, Math.min(98, py)) // Clip py between 0-98
vy = 0;
}
dot = document.getElementsByClassName("indicatorDot")[0]
dot.setAttribute('style', "left:" + (px) + "%;" +
"top:" + (py) + "%;");
});
}
});
}
</script>
</head>
<body style="background-color:lightblue;">
<button id="accelPermsButton" style="height:50px;" onclick="getAccel()">
<h1>Get Accelerometer Permissions</h1>
</button>
<div class="indicatorDot" style="left:30%; top:30%;"></div>
<p id="demo"></p>
</body>
</html>