Skip to content

Instantly share code, notes, and snippets.

@c4tachan
Last active November 20, 2019 19:08
Show Gist options
  • Save c4tachan/96ad194f0b90e79195ce to your computer and use it in GitHub Desktop.
Save c4tachan/96ad194f0b90e79195ce to your computer and use it in GitHub Desktop.
Implementation of reading the orientation of a device using JavaScript. Eventually, this will also include code to open a web socket and transmit that information to a server. This script was shamelessly stolen and modified from the source code of http://www.html5rocks.com/en/tutorials/device/orientation/deviceorientationsample.html
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
init();
var count = 0;
function init()
{
// Start by creating the websocket we will use
if ("WebSocket" in window)
{
// Let's set it up so that the websocket port will be on the hosting port +1
// We should verify that both ports are available before starting to host the page
// from inside of the opentrack software.
var ws = new WebSocket(window.location.host + ":" + String(Number(window.location.port) + 1));
if (window.DeviceOrientationEvent)
{
// Listen for the deviceorientation event and handle the raw data
window.addEventListener('deviceorientation', function(eventData)
{
// Let's build an array to send through the websocket we created.
var orientationVector = [eventData.alpha, eventData.beta, eventData.gamma];
// From what I have read, it seems I can send a blob of binary data through a websocket,
// so let's just send the raw binary data of the array
ws.send(orientationVector);
}, false);
}
else
{
alert("Not supported on your device or browser. Sorry.");
}
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment