Game Development Reference
In-Depth Information
//updated HTML elements
<div id="gameWrapper">
<img id="bg" src="img/bg.jpg">
<canvas id="canvas" width="550" height="500"></canvas>
</div>
There are a several approaches when it comes to preparing for screen sizes, but we'll be looking at just one.
The technique I prefer is to scale the canvas to adjust to screen sizes and to adjust upon orientation changes.
Listing 12-4 adds the code that listens for orientation and screen resizing events.
Listing 12-4. Checking For Devices and Desktop to Set the Appropriate Event Listeners
function optimizeForTouchAndScreens () {
if (typeof window.orientation !== 'undefined') {
window.onorientationchange = onOrientationChange;
if (createjs.Touch.isSupported()) {
createjs.Touch.enable(stage);
}
onOrientationChange();
}
else {
window.onresize = resizeGame;
resizeGame();
}
}
This function is updated to check if the user is on a desktop or a device. First, if it's a device, the onorientationchange
event is set on window , which will trigger when the user moves from portrait to landscape, or vice versa. The function
onOrientationChange function is called, which will handle this event. You'll want to manually call this function as
well because you won't get the change event when the page is first loaded, which is needed to trigger the initial scaling
and positioning of the canvas.
In the case of a desktop, there will never be an orientation change. However, you still want the game to respond to
window resizing. The resizeGame function is called on this event, and it is also initially called when the page is loaded
to properly adjust the canvas.
The onOrientationChange and resizeGame functions are shown in Listing 12-5.
Listing 12-5. The onOrientation and resizeGame Functions Adjust the Size of the Game to Fit the Screen
function onOrientationChange() {
setTimeout(resizeGame, 100);
}
function resizeGame() {
var nTop, nLeft, scale;
var gameWrapper = document.getElementById('gameWrapper');
var bg = document.getElementById('bg');
var w = window.innerWidth;
var h = window.innerHeight;
var nWidth = window.innerWidth;
var nHeight = window.innerHeight;
var widthToHeight = canvas.width / canvas.height;
var nWidthToHeight = nWidth / nHeight;
 
Search WWH ::




Custom Search