Gamedev Phaser Content Kit

Article 02: Scaling

We can make the game scale on any mobile device right at the beginning, so we don't have to worry about it later. That way it doesn't matter what the screen size there is - the game will adjust accordingly. There's a special scale object available in Phaser with a few handy methods and variables:

function preload() {
    game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    game.scale.pageAlignHorizontally = true;
    game.scale.pageAlignVertically = true;
}

The scaleMode have a few different options on how the Canvas can be scaled:

The first one, NO_SCALE does exactly that - nothing is scaled. The EXACT_FIT mode scales the Canvas to fill all the available space both vertically and horizontally, but it's not keeping the aspect ratio. The SHOW_ALL mode is something we will use as it scales the Canvas, but keeps the aspect ratio untouched, so the images won't be skewed like in the previous mode. There might be black stripes visible on the edges of the screen, but we can live with that. The RESIZE mode is a little bit more complicated as it creates the Canvas with the size of the available width and height, so you have to place the objects inside your game dynamically, which might be confusing at the beginning. The USER_SCALE is an extra mode that allows you to have custom dynamic scaling, calculating the size, scale and ratio on your own.

Two other lines of code in the preload function are responsible for aligning the Canvas element horizontally and vertically, so it is always centered on screen no matter how much space it take.

We can also add the background color to our Canvas, so it won't stay black. The stage object have the backgroundColor property that we can set using the CSS color definition syntax:

game.stage.backgroundColor = '#eee';

Compare your code

You can check the finished code for this lesson for yourself in the live demo below, and play with it to understand better how it works:

Next steps

Now we've set up the scaling, so let's continue to the third lesson and work out how to load the assets and print them on screen.