HTML and CSS Reference
In-Depth Information
Chapter 24
Querying Device Orientation and
Acceleration
What's in This Chapter?
• Learning about screen orientation
• Understanding the device orientation API
• Playing with device orientation
• Combatting device rotation
Wrox.com Code Downloads for this Chapter
The wrox.com code downloads for this chapter are found at www.wrox.com/rem-
title.cgi?isbn=9781118301326 on the Download Code tab. The code is in the Chapter 24 download and individu-
ally named according to the names throughout the chapter.
Introduction
Using the orientation of your mobile device to control a game was one of the first “wow” moments of the smart-
phone gaming era. With the support for device orientation and acceleration in the browser, that capability is now
within your reach as an HTML5 game developer. This chapter examines the DeviceOrientation event API, which
has two useful events: device orientation and device motion. A third event, compass, is also available, but unless
you have a long-running application that needs precise direction details, you can safely ignore this event.
Looking at a Device Orientation
Before examining the DeviceOrientation Event API, it's worth a brief look at the window.orientation
property. This property won't tell you the exact angle you hold your device at, but it can tell you an angle that
indicates which way—portrait or landscape—your device's screen is oriented.
You can also listen for orientationchange events to detect when the device is rotated to a different con-
figuration. To try this, add the following to any page that has jQuery loaded on it:
$(window).on("orientationchange",function(e) {
alert(window.orientation);
});
Search WWH ::




Custom Search