Untitled
1 month ago in Plain Text
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

<style type="text/css">
.garden {
position: relative;
width : 200px;
height: 200px;
border: 5px solid #CCC;
border-radius: 10px;
}

.ball {
position: absolute;
top : 90px;
left : 90px;
width : 20px;
height: 20px;
background: green;
border-radius: 100%;
}

</style>

<title>Detecting device orientation - Orientation_example - code sample</title>
</head>
<body>

<div class="garden">
<div class="ball"></div>
</div>

<pre class="output"></pre>



<script>
var ball = document.querySelector('.ball');
var garden = document.querySelector('.garden');
var output = document.querySelector('.output');

var maxX = garden.clientWidth - ball.clientWidth;
var maxY = garden.clientHeight - ball.clientHeight;

function handleOrientation(event) {
var x = event.beta; // In degree in the range [-180,180]
var y = event.gamma; // In degree in the range [-90,90]

output.innerHTML = "beta : " + x + "\n";
output.innerHTML += "gamma: " + y + "\n";

// Because we don't want to have the device upside down
// We constrain the x value to the range [-90,90]
if (x > 90) { x = 90};
if (x < -90) { x = -90};

// To make computation easier we shift the range of
// x and y to [0,180]
x += 90;
y += 90;

// 10 is half the size of the ball
// It center the positioning point to the center of the ball
ball.style.top = (maxY*y/180 - 10) + "px";
ball.style.left = (maxX*x/180 - 10) + "px";
}

window.addEventListener('deviceorientation', handleOrientation);

</script>

</body>
</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