Game Development Reference
In-Depth Information
The other case is that the new ratio is smaller, meaning the browser window is too high. In that case,
you need to recalculate the height:
newHeight = newWidth / widthToHeight;
Now that you've calculated the correct width and height, you first change gameArea div so it has this
height and width. You do that as follows, simply by editing the style of the element:
gameArea.style.width = newWidth + 'px';
gameArea.style.height = newHeight + 'px';
In order to display the gameArea element in the middle of the screen, you also define margins, as follows:
gameArea.style.marginTop = (window.innerHeight - newHeight) / 2 + 'px';
gameArea.style.marginLeft = (window.innerWidth - newWidth) / 2 + 'px';
gameArea.style.marginBottom = (window.innerHeight - newHeight) / 2 + 'px';
gameArea.style.marginRight = (window.innerWidth - newWidth) / 2 + 'px';
You divide the difference between the new width and height and the actual width and height by 2
and set those values as the margins. For example, if the desired game screen width is 800 but the
window is actually 900 pixels wide, you create a margin of 50 pixels on each side so that the element
is drawn in the middle of the screen. Finally, you change the size of the canvas so that it has the
desired width and height (and thus the correct ratio):
gameCanvas.width = newWidth;
gameCanvas.height = newHeight;
The scale at which the sprites should be drawn can now be calculated easily. You define a property
that does this for you:
Object.defineProperty(Canvas2D_Singleton.prototype, "scale",
{
get: function () {
return new Vector2(this._canvas.width / Game.size.x,
this._canvas.height / Game.size.y);
}
});
When you draw an image, you simply apply this scale before you perform the drawing operation.
This is done by adding a few lines of code to the Canvas2D.drawImage method—one line for retrieving
the scale, and one for applying it:
var canvasScale = this.scale;
this._canvasContext.scale(canvasScale.x, canvasScale.y);
Do the same thing in the Canvas2D.drawText method. For the complete code, look at the JewelJam1
example belonging to this chapter.
 
Search WWH ::




Custom Search