In mobile games, we often need to tilt or rotate mobile devices to control the elements in the game. For example, in a racing game, we need to tilt the left and right sides to control the right and right steering of the car, in the temple escape game, we also need to tilt our mobile devices to control the movement of the characters. Imagine that if the tilt of the device allows the game screen to rotate and the game screen needs to be re-painted to adapt to the screen size change, it would be a disaster for the game designers, however, in the Web field, no API can control the Screen direction. At this time, the Screen Orientation API introduced by W3C is on the stage.
What is Screen Orientation API?
Screen Orientation API is an API that allows Web developers to control the Orientation of Screen rotation. developers can use this API to detect the current direction of the Screen and receive a message notification when the Screen direction changes, you can also use the API to lock the screen to a specified status. At the time of writing this article, mainstream browsers have partially supported or decided to support this API. FireFox 26 and IE 11 both support the lockOrientation and unlockOrientation APIs and Crosswalk 4 (based on Chromium Web Runtime) this API is also supported. Chrome on Android is also implementing this API, which is expected to be completed by the first quarter of 2014.
Sample Code:
// When the screen is locked, the screen is in portrait mode and cannot be rotated. The screen will not be switched to Landscape mode. Window. screen. lockOrientation (["portrait-primary", "portrait-secondary"]); // the screen will not be switched to portrait mode if the screen is locked in Landscape mode and the devices cannot rotate. Window. screen. lockOrientation (["landscape-primary", "landscape-secondary"]); // cancels the screen lock and returns to the original status, window. screen. unlockOrientation ();
In addition, note that the document specification of the Screen Orientation API is still in the development stage, and the browser implementation may have a prefix. For example, Firefox has a moz prefix and IE has a ms prefix. Before use, we need to add some code to ensure better compatibility.
For example:
window.screen.lockOrientation = screen.lockOrientation ||screen.mozLockOrientation || screen.msLockOrientation;window.screen.unlockOrientation = screen.unlockOrientation|| screen.mozUnLockOrientation || screen.msUnLockOrientation;