Accessing the gyroscope and accelerometer using JavaScript

With the advent of "mobile" devices such as the iPad, iPhone and all the gazillion Android devices, an increasing demand for browser-applications to sport the features and functionality native applications arises. In this article I'll have a quick look at one of these features, namely «device orientation». First of all, take a look at the demo. In this demo I'm using the "deviceorientation" event listener of the «window» object to listen for orientation events. Orientation events are in short events triggered when your device is twisting and turning, sort of. In my iPhone, these events originate in the accelerometer and the gyroscope. For your phone this might be different, but it doesn't matter as the API's for accessing the data are pretty much the same and part of the «DeviceOrientation Event Specification». Note that this demo is only tested on the iPhone 4, so if you have something else it might not work. Let's get to it then.
window.addEventListener('deviceorientation', orientationHandler, false);

First of all we need to add an event listener for the «device orientation» event. This event is fired by the «window» object as mentioned above. We then simply set up our event handler.

function orientationHandler(e)
{
 image.style.webkitTransform = "perspective(500) 
rotateZ("+e.alpha+"deg) 
rotateX("+e.beta+"deg) 
rotateY("+e.gamma+"deg)";
}

There are three properties of the «orientation event» we want to get at.

  • «alpha» - This is rotation about the Z axis. In other words left and right rotation.
  • «beta» - This is rotation about the X axis. This means how much you are tilting the device towards you.
  • «gamma» - This is the rotation about the Y axis, or the angle of the device screen if you may.
There are also two other properties present in iOS 5 which gives you access to the compass and it's accuracy, but those are not used in this example.

The «perspective(500)» transform simply defines how "far away" from the object you are when it's rotated, or the depth if you like. Since the properties of the «device orientation» event correlates to the values handled by the CSS transform properties, no calculation is needed. Try it out! (Should work on iPhone 4 and iPad 2)

References:

No comments: