A motion interface with HTML5

26 Mar 2011

I was looking at the HTML5 Rocks slides yesterday and came across the Device Orientation slide which allows a compliant browser to access the orientation data from an accelerometer on a supported device. Then I noticed the Chrome logo moving and saw that Chrome is able to access the sensor data from my MacBook's Sudden Motion Sensor. Awesome! I had no idea this data was available to the browser.

I remembered seeing a few articles a while ago (when Apple started putting the accelerometers in MacBooks) where people had got access to the raw data and used it for such things as turning their machines into lightsabres and changing desktops by hitting the sides of the laptop. For some reason the latter always stuck in my head so when I saw the device orientation event in HTML5, I thought I could mimic this behaviour. Getting the sensor data is very simple, first you need to create the event handler.

var orientationListener = function(event) {
    var alpha = event.alpha;
    var beta = event.beta;
    var gamma = event.gamma;
    // Do stuff here
}

You can then bind it to the "deviceorientation" event handler like so

window.addEventListener('deviceorientation', this.orientationListener, false);

Easy! For some reason, the alpha value is always null. The beta value represents tilting the device left and right (roll) and the gamma value towards and away from you (pitch).

I wrote a simple Flickr browser which uses left and right tilting to browse a set of images. Here's a video of it in action.

Comments