Using Device Orientation in HTML5

Ahmet Mermerkaya

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.

if (window.DeviceOrientationEvent) {
  // Our browser supports DeviceOrientation
} else {
  console.log("Sorry, your browser doesn't support Device Orientation");
}

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.

<!DOCTYPE html>
<html>
  <body>
    <canvas id="myCanvas" width="360" height="450" style="border:1px solid #d3d3d3;">
    </canvas>
    <script>
      if (window.DeviceOrientationEvent) {
        window.addEventListener("deviceorientation", deviceOrientationListener);
      } else {
        alert("Sorry, your browser doesn't support Device Orientation");
      }
    </script>
  </body>
</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

Alpha

The alpha angle represents rotation around the z-axis. Therefore, any rotation along the z-axis causes the alpha angle to change. The alpha angle can range between 0 and 360 degrees. Alpha is 0 when the top of the device is pointed directly to Earth’s North Pole. The following image shows alpha rotation.

Alpha Rotation

Beta

Rotation around the x-axis cause the beta angle to change. The range of beta is between -180 and 180 degrees. Beta is zero when the device is parallel to Earth’s surface. An example of this would be lying on top of a table. An illustration of the beta angle is shown below.

Beta Rotation

Gamma

The gamma angle is associated with the y-axis. This angle ranges from -90 to 90 degrees, and is zero when the device is parallel to the Earth’s surface. The gamma value changes when the device is rotated as shown in the following figure.

Gamma Rotation

The deviceorientation Event Handler

The next step is to implement the handler for the deviceorientation event. This function is shown in the following code sample. This code begins by clearing the entire canvas. Next, a circle and rectangles are drawn according to the values of alpha, beta, and gamma. The details of how the canvas element works is beyond the scope of this article, but the reader is encouraged to check out this SitePoint article.

function deviceOrientationListener(event) {
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");

  ctx.clearRect(0, 0, c.width, c.height);
  ctx.fillStyle = "#FF7777";
  ctx.font = "14px Verdana";
  ctx.fillText("Alpha: " + Math.Round(event.alpha), 10, 20);
  ctx.beginPath();
  ctx.moveTo(180, 75);
  ctx.lineTo(210, 75);
  ctx.arc(180, 75, 60, 0, event.alpha * Math.PI / 180);
  ctx.fill();

  ctx.fillStyle = "#FF6600";
  ctx.fillText("Beta: " + Math.round(event.beta), 10, 140);
  ctx.beginPath();
  ctx.fillRect(180, 150, event.beta, 90);

  ctx.fillStyle = "#FF0000";
  ctx.fillText("Gamma: " + Math.round(event.gamma), 10, 270);
  ctx.beginPath();
  ctx.fillRect(90, 340, 180, event.gamma);
}

Putting It All Together

The finished product is shown below. This page has no external dependencies, so just open it up in the device orientation friendly browser of your choice, and enjoy!

<!DOCTYPE html>
<html>
  <body>
    <canvas id="myCanvas" width="360" height="450" style="border:1px solid #d3d3d3;">
    </canvas>
    <script>
      function deviceOrientationListener(event) {
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");

        ctx.clearRect(0, 0, c.width, c.height);
        ctx.fillStyle = "#FF7777";
        ctx.font = "14px Verdana";
        ctx.fillText("Alpha: " + Math.Round(event.alpha), 10, 20);
        ctx.beginPath();
        ctx.moveTo(180, 75);
        ctx.lineTo(210, 75);
        ctx.arc(180, 75, 60, 0, event.alpha * Math.PI / 180);
        ctx.fill();

        ctx.fillStyle = "#FF6600";
        ctx.fillText("Beta: " + Math.round(event.beta), 10, 140);
        ctx.beginPath();
        ctx.fillRect(180, 150, event.beta, 90);

        ctx.fillStyle = "#FF0000";
        ctx.fillText("Gamma: " + Math.round(event.gamma), 10, 270);
        ctx.beginPath();
        ctx.fillRect(90, 340, 180, event.gamma);
      }

      if (window.DeviceOrientationEvent) {
        window.addEventListener("deviceorientation", deviceOrientationListener);
      } else {
        alert("Sorry, your browser doesn't support Device Orientation");
      }
    </script>
  </body>
</html>

Conclusion

This article has introduced the device orientation API. This API is simple and fairly well supported in modern browsers. By harnessing the power of device orientation, your web pages can be made more responsive and powerful. In addition to the demo on this page, I encourage you to look over this article’s references, listed below.

References

Article Demo
http://www.w3.org/TR/orientation-event/
https://developer.mozilla.org/en-US/docs/WebAPI/Detecting_device_orientation

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.linkedin.com/in/christophermregan Christopher Regan

    How simply simple and wonderful.
    Awesome, and thank you, Ahmet.

  • Rich T

    Great article and nice demo!

    I also wrote an article on practical usage of Device Orientation for 3D use cases and how we can account for screen orientation changes that should act as a good follow on article for your readers: http://dev.opera.com/articles/w3c-device-orientation-usage/

    There’s also a virtual reality demo built on that article that works well across mobile browsers at https://richtr.github.io/threeVR/examples/vr_basic.html

  • Derek Nassler

    In the code above on line 14 there is a typo. It should read as Math.round not Math.Round. Otherwise it did not work for me and was a little frustrating.

    ctx.fillText(“Alpha: ” + Math.round(event.alpha), 10, 20);