Created
April 17, 2014 08:40
-
-
Save tkojitu/10965373 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- https://developer.mozilla.org/en-US/docs/WebAPI/Detecting_device_orientation --> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<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> | |
</head> | |
<body> | |
<div class="garden"> | |
<div class="ball"></div> | |
</div> | |
<pre class="output"></pre> | |
<script src="DetectDevOri.js"></script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = (maxX * x / 180 - 10) + "px"; | |
ball.style.left = (maxY * y / 180 - 10) + "px"; | |
} | |
window.addEventListener('deviceorientation', handleOrientation); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment