/

Phaser: The Canvas

Phaser: The Canvas

Phaser games utilize the HTML <canvas> element for rendering.

If you’re unfamiliar with the Canvas API, I discuss it in detail in my Canvas API tutorial.

When working with Phaser, we create a canvas with a specific width and height, and then draw on it. While CSS cannot be used to style elements within the canvas, Phaser (along with other canvas-based libraries) abstracts away many of the low-level details, allowing us to focus on the application code.

To initialize a Phaser game, we call the Game static method on the Phaser object:

1
new Phaser.Game()

We pass an object literal with various configuration options to this function:

1
new Phaser.Game({})

Within this configuration object, we can specify several properties. For example, we can set the width and height of the canvas:

1
2
3
4
new Phaser.Game({
width: 450,
height: 600
})

Another property we can include is backgroundColor, which accepts a hexadecimal value, such as 0x000000 for black.

Colors are similar to CSS colors, but you need to prepend 0x to let JavaScript know it’s a hexadecimal number.

tags: [“Phaser”, “Canvas”, “HTML5”, “Game Development”, “JavaScript”]