Game Development Reference
In-Depth Information
Listing 12-7. Factoring the Direction in Which to Scale and Position the Game
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";
}
If the nWidthToHeight value (the current width-to-height ratio of the window) is greater than widthToHeight
(the desired width-to-height ratio of your game), then you know that the window is too wide to attempt to scale the
canvas to the sides of the window. You then calculate nWidth by using the height of the window. Now that you know
what the new width of the game should be, scale is calculated by dividing it by the canvas width. This scale value is
the ultimate goal here, and will be used to scale the canvas.
Not although the canvas will be scaling on window resizing and orientation changes, the original width and the
height properties on your canvas will always remain the same.
Now that the scale has been calculated, the game's positioning needs to be adjusted. In this first case, where
the canvas will be hugging the top and bottom of the window, its left position needs to be updated so it sits perfectly in
the middle. This is set to nLeft by finding the middle of the window and subtracting half of the canvas' new width.
You've done this often when centering display objects on the stage. Figure 12-1 shows the results on an Android Nexus
device and an iPhone 5. Note that in the case of the iPhone running iOS7 (the bottom image),
full screen is launched automatically when rotated to landscape orientation.
 
 
Search WWH ::




Custom Search