Game Development Reference
In-Depth Information
if (nWidthToHeight > widthToHeight) {
nWidth = nHeight * widthToHeight;
scale = nWidth / canvas.width;
nLeft = (w / 2) - (nWidth / 2);
gameWrapper.style.left = (nLeft) + "px";
gameWrapper.style.top = "0px";
}
else {
nHeight = nWidth / widthToHeight;
scale = nHeight / canvas.height;
nTop= (h / 2) - (nHeight / 2);
gameWrapper.style.top = (nTop) + "px";
gameWrapper.style.left = "0px";
}
canvas.setAttribute("style", "-webkit-transform:scale(" + scale +
")");
bg.setAttribute("style", "-webkit-transform:scale(" + scale + ")");
window.scrollTo(0, 0);
}
When the user rotates their device, or resizes their browser window on desktop, the resizeGame function is
ultimately called. The reason for the intermediate onOrientationChange function is because you'll need a short
timeout set after the onorientationchange event is handled. This is because some device browsers will run the event
handler code before the window actually rotates and resizes. This is problem because you need the new window sizes
to properly resize the canvas.
A series of variables are first set at the top of the function (see Listing 12-6).
Listing 12-6. The resizeGame Function's Local Variables
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;
A reference to the div that the holds the game elements is first referenced. You will need this to reposition the
game after its resized. In this particular game, an image was created in the DOM as the background for the game.
This image will also need to be resized to match the new size of the canvas.
The current width and height of the window is set to the variables w , nWidth , h , and nHeight . Next, the
widthToHeight variable is set to the ratio of the game, which can be retrieved by referencing the width and height of
the canvas. Finally, nWidthToHeight is set the current ratio of the window.
In a nutshell, the desired game ratio is being set along with the current window ratio. These values will determine
how the canvas should be scaled and placed in the screen. With the appropriate values set, a conditional is written to
determine how the scaling should be handled (see Listing 12-7).
 
Search WWH ::




Custom Search