Drawing Graphics in Phaser (Part 1)


Using Phaser Graphics

In this quick tutorial, we’re going to take a look at how to draw primitives using Phaser’s Graphics class.

Drawing your shape is almost always the same, but there is a difference between creating the graphics.

You can add it directly to the stage, or make an instance of the graphics class, then add it later. I prefer to do the latter as you can still manipulate the graphics object before it gets added to the display list and rendered to the screen.

Lets look at some code examples.

// create a group for our graphics
let group = this.add.group();
// created on the world
let graphics = this.game.add.graphics(); // adds to the world stage
graphics.lineStyle(2, 0xFFFFFF, 1);
graphics.drawRect(200, 200, 250, 250);
group.add(graphics) // moves from world stage to group as a child
// create an instance of graphics, then add it to a group
let graphics2 = this.game.make.graphics();
graphics2.lineStyle(2, 0xFFFFFF, 1);
graphics2.drawRect(500, 200, 250, 250);
group.add(graphics2); // added directly to the group as a child

Colouring In

So it’s a fairly basic implementation of graphics. We make the new graphics object, then set the line style. the lineStyle function accepts three parameters – line width, line colour (hex) and alpha. Then we call the drawRect function which takes four parameters. X and Y position and width and height.

If you want to fill the shape with colour, you can use the beginFill function, which accepts a hex colour and an opacity. You then just need to call the endFill function to tell the graphics to fill in the shape you’ve just drawn.

let graphics = this.game.make.graphics();
graphics.lineStyle(2, 0xFFFFFF, 1);
graphics.beginFill(0xFF700B, 1);
graphics.drawRect(200, 200, 250, 250);


Error code 89: Invalid or expired token.

Stay Updated