HTML Device Orientation Project
For a class assignment, we were asked to create a project that demonstrated the usage of device orientation events. In this project, the device orientation was used to manipulate a “rolling ball” on the screen.
To try the demo, click here. Note that the project was programmed such that it only works on a mobile device (e.g. phones, tablets).
For the source code, click here. Click through for more documentation.
After loading the demo, it will ask you to rotate your device to landscape mode. After rotating, tap the screen to begin, and you can begin tilting your device to move a “marble” around on the screen. Rotating back to portrait mode will “pause” the demo.
Each time you resume the demo from a paused state, it will recalibrate the center position based on how the device is held.
The demo can be found here.
This project used media queries to determine what kind of device is being used by the user. In CSS, different styles were applied based on the device type. For example, the first block would apply to phones, and the second block would apply to tablets. Note that if using a tablet, it would apply the phone styling first, then also apply the tablet styling on top of it.
Device Orientation Change - Portrait/Landscape
To detect when a device changes orientation (from landscape to portrait and vice versa), I employed the use of the window.onorientationchange event. All modern mobile browsers support this event.
Once you have determined that the device supports orientation events, you can then receive notifications of when a device changes orientation and subsequently perform an action.
Device Orientation Change - Ball Movement
In addition to receiving notifications when a device changes orientation from landscape to orientation, you can add a listener to receive notifications whenever a device changes its orientation at all.
Instead of using a timer loop to create animations, there is a feature to allow the browser to notify your application when it is ready for the next frame of the animation.