Phaser: The Canvas

By

Learn how Phaser renders your game inside an HTML canvas, and how to configure it with new Phaser.Game by setting width, height, and backgroundColor.

~~~

This post is part of a Phaser series. Click here to see the first post of the series.

Phaser games are rendered inside an HTML <canvas> element. Phaser creates this element for you when the game starts, and draws every frame of the game into it.

If you’re new to Canvas, I talk in details about it in the Canvas API tutorial.

We create a canvas, with a specific set of width/height, and we draw into it.

We can’t use CSS to style elements, but we have to use a more low level and difficult API.

Luckily Phaser (and other libraries that use Canvas under the hood) abstract away all the tiny details, so we can focus on the application code.

Creating the game

We initialize a Phaser game by calling the Game static method on the Phaser object:

new Phaser.Game()

We must pass to this function an object literal with a set of configuration options:

new Phaser.Game({})

In this configuration object we can set various properties.

Setting the canvas size

To start with, we can set the width and height of the canvas:

new Phaser.Game({
  width: 450,
  height: 600
})

If you don’t set them, Phaser creates a 1024x768 canvas by default. I recommend setting them explicitly, so the game size is a decision and not an accident.

Choosing the renderer

Phaser can draw using WebGL, or using the 2D Canvas API. The type property picks one:

new Phaser.Game({
  type: Phaser.AUTO,
  width: 450,
  height: 600
})

Phaser.AUTO is what you want in most cases. It uses WebGL when the browser supports it, and falls back to Canvas otherwise. You can force one renderer with Phaser.WEBGL or Phaser.CANVAS.

Either way, the game still lives inside a <canvas> element. The type only changes the drawing API Phaser uses internally.

Where does the canvas go?

By default Phaser appends the canvas to the document body. In a real page you usually want it inside a specific element. Pass the id of that element in the parent property:

new Phaser.Game({
  width: 450,
  height: 600,
  parent: 'game'
})
<div id="game"></div>

Be careful with the loading order. If your script runs before that element exists in the page, Phaser can’t find it, and appends the canvas to the body instead. Load the script at the end of the body to avoid this.

Setting the background color

Another property we can pass is backgroundColor, which accepts an hexadecimal value, like 0x000000 for black:

new Phaser.Game({
  width: 450,
  height: 600,
  backgroundColor: 0x000000
})

Colors are similar to CSS colors, but you need to prepend 0x so JS knows it’s an hexadecimal number.

A CSS-style string like '#000000' works too.

Tagged: Phaser · All topics
~~~

Related posts about phaser: