Ahmet's articles

  1. Using Device Orientation in HTML5

    Device orientation is yet another cool feature of HTML5. Device orientation allows a device to detect its physical orientation with respect to gravity. If you’ve ever rotated a smart phone or tablet, and the screen has rotated in response, then you’ve seen device orientation in action. Orientation is measured using three angles – alpha, beta, and gamma – that describe the device’s current position. We can use these angles in HTML5 enabled web apps.

    In this article, we are going to write a simple web app that utilizes device orientation. This app is going to include circular and rectangle shapes whose sizes change according to the values of alpha, beta, and gamma. The following two screenshots illustrate the behavior of our example app depending on orientation. Don’t worry if you don’t understand what the angles mean, as you’ll learn along the way.

    Screenshot One
    Screenshot Two

    Browser Compatibility

    Before using the device orientation API, you need to make sure your browser supports it. You can easily check Can I Use.com to determine if your browser supports this API. However, your users are unlikely to do this, so you need to build something into your code. The following code can be used to dynamically detect support for the device orientation API.

    [js]
    if (window.DeviceOrientationEvent) {
    // Our browser supports DeviceOrientation
    } else {
    console.log(“Sorry, your browser doesn’t support Device Orientation”);
    }
    [/js]

    Getting Started

    Let’s begin by creating a skeleton HTML file that will hold our application. Notice the use of a canvas element, which will hold our shapes. The script element detects whether or not the user’s browser supports device orientation. If it does, then we add a deviceorientation event listener – more on this in a below.

    [html]
    < !DOCTYPE html>







    [/html]

    The deviceorientation Event

    The deviceorientation event, which our code is listening for, is fired when the device orientation changes. When this event is fired, our event handler, deviceOrientationListener() is invoked. A DeviceOrientationEvent object is the only argument passed to our handler. The previously mentioned alpha, beta, and gamma angles are defined as properties of the DeviceOrientationEvent. Before moving on, it’s time to learn more about these mysterious angles.

    The Alpha, Beta, and Gamma Angles

    Before explaining what each of the angles represents, we need to define the space in which they exist. The following image, courtesy of Mozilla, shows the 3D coordinate system used on mobile devices.

    Axes