Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Sprites and Animation

Phaser Shapes, Text and Graphics Objects

Draw with Phaser game objects: rectangles, circles, stars, lines, the Graphics API, styled and wrapped text, plus the shared properties every game object has.

Before you have any artwork, you already have everything needed to build a playable prototype: shapes and text. Many successful small games never use anything else; a clean geometric style is a legitimate look. This lesson teaches the built-in shape objects, the lower-level Graphics drawing API, styled text, and the properties that every game object shares.

Game objects and the factory

Every visible thing in Phaser is a game object. You create one with the factory this.add (which also puts it on the scene's display list so it is drawn) and you get the object back to configure:

JavaScript
const box = this.add.rectangle(200, 120, 80, 50, 0xef4444);   // x, y, width, height, color
box.setAlpha(0.8).setAngle(15);                                // methods chain

Almost every set... method returns the object itself, so you can chain calls, as in the previous line.

Built-in shapes

Shape game objects are retained: you create them once and they remember their size, fill and stroke. The common ones:

Factory call Shape
add.rectangle(x, y, w, h, fill, alpha) rectangle
add.circle(x, y, radius, fill) circle
add.ellipse(x, y, w, h, fill) ellipse
add.triangle(x, y, x1, y1, x2, y2, x3, y3, fill) triangle from three points
add.star(x, y, points, innerR, outerR, fill) star
add.polygon(x, y, points, fill) any polygon from a point list
add.line(x, y, x1, y1, x2, y2, color) a line segment
add.arc(x, y, radius, startAngle, endAngle, anticlockwise, fill) pie slice or arc
add.grid(x, y, w, h, cellW, cellH, fill) a grid pattern

Style methods: setFillStyle(color, alpha), setStrokeStyle(lineWidth, color, alpha), and the shared setAlpha, setScale, setAngle. Colors are numbers in hexadecimal notation, 0xRRGGBB.

A shape gallery

Notice the triangle: its three points are in local coordinates relative to the object's own box, not to the screen. Most shapes sit on their x, y center position because shapes default to origin 0.5, but lines are an exception; set .setOrigin(0) for them as the example does.

Properties every game object shares

All game objects (shapes, text, images, sprites) share a core set of properties and methods:

Property Meaning Setter
x, y position setPosition(x, y)
scaleX, scaleY size multiplier setScale(s) or setScale(sx, sy)
angle rotation in degrees setAngle(deg)
rotation rotation in radians setRotation(rad)
alpha opacity 0 to 1 setAlpha(a)
visible draw or not setVisible(bool)
depth draw order; higher is on top setDepth(n)
originX, originY the pivot, 0 to 1 setOrigin(x, y)
scrollFactor how much cameras move it setScrollFactor(f)
name, data your own labels and values setName, setData(key, v)

Two of them cause the most confusion:

  • depth: objects are drawn in the order they were added, so later ones cover earlier ones. setDepth(10) overrides that; objects with equal depth keep creation order.
  • origin: where inside the object its x, y refers. (0.5, 0.5) is the center (rotation and scaling happen around it), (0, 0) the top-left corner. A health bar usually uses origin (0, 0.5) so it grows to the right from a fixed left edge.

The Graphics object

Shapes are convenient, but sometimes you need free drawing: a curve, a custom outline, many lines. For that Phaser has the Graphics object, with an API close to the HTML canvas:

JavaScript
const g = this.add.graphics();
g.lineStyle(3, 0xffffff, 1);           // width, color, alpha
g.fillStyle(0x22c55e, 1);
g.fillRect(10, 10, 100, 40);
g.strokeCircle(200, 30, 20);
g.beginPath();
g.moveTo(10, 100);
g.lineTo(60, 80);
g.lineTo(110, 100);
g.strokePath();                        // draw the path

Graphics are immediate: each call adds drawing commands to one object, and the pixels are not separate objects you can move. Use g.clear() to wipe it and draw again. A single Graphics object redrawn every frame is fine for things like a laser line or a debug overlay, but thousands of commands per frame get slow. If the picture does not change, draw it once and convert it into a texture with generateTexture, as you did in Loading Assets.

Useful methods: fillRect, fillRoundedRect, fillCircle, fillTriangle, fillPoints, strokeRect, strokeCircle, lineBetween, arc, closePath, plus fillGradientStyle for gradient fills of rectangles.

Drawing with Graphics

Text objects

this.add.text(x, y, content, style) creates a text object. Text is drawn to a hidden canvas and uploaded as a texture, so changing it often is more expensive than moving it. The style object accepts the CSS font options you know:

JavaScript
this.add.text(40, 40, 'Level 3\nGet ready!', {
  fontFamily: 'Georgia, serif',
  fontSize: '32px',
  fontStyle: 'bold',
  color: '#fde047',
  stroke: '#000000',
  strokeThickness: 6,
  align: 'center',
  backgroundColor: '#00000088',
  padding: { x: 12, y: 8 },
  shadow: { offsetX: 3, offsetY: 3, color: '#000', blur: 4, fill: true },
  wordWrap: { width: 300 },
  lineSpacing: 6
});

Handy methods: setText(string or array of lines), setColor, setFontSize, setStyle, setWordWrapWidth, setAlign, setLineSpacing. A text object's width and height tell you its measured size, which helps center buttons.

Fonts: only fonts installed on the player's device or loaded with CSS @font-face are available. If a web font is not ready when the text is created, Phaser measures the fallback font. Load custom fonts first (the browser's document.fonts.load or a font-loader plugin) and then create the text.

For fast, crisp, heavily updated text (score counters, pixel fonts) use bitmap text: you load a font image plus its XML/JSON description with this.load.bitmapFont(...) and then this.add.bitmapText(x, y, 'fontKey', 'SCORE'). It renders through the same fast path as sprites.

Styled and wrapped text

The button is just a text object with a background color and padding, made interactive. Hover and press states come from the three pointer events. That is enough for a menu.

Which should you use?

flowchart TD
  A["Need to draw something"] --> B{"Will it move,<br/>get clicks or physics?"}
  B -->|Yes| C{"Simple geometry?"}
  C -->|Yes| D["Shape game object"]
  C -->|No| E["Image or sprite"]
  B -->|No, static art| F{"Many commands?"}
  F -->|Yes| G["Graphics once, then generateTexture"]
  F -->|No| H["Graphics object"]

Shapes for movable geometry, sprites for art, Graphics for static or debug drawing.

Common mistakes

  • Drawing in update without clear(). Graphics commands pile up every frame and the game slows to a crawl.
  • Creating new text every frame. Make one text object and call setText.
  • A triangle in the wrong place. Its points are local; use x, y to position the whole object.
  • Forgetting 0x colors. add.circle(10, 10, 5, '#ff0000') does not work for fills; use 0xff0000. Text styles are the opposite: they take CSS strings.
  • Shapes with physics. Add a body with this.physics.add.existing(shape) (see Arcade Physics Basics); circles get round bodies automatically.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the default origin of most Phaser shapes and images?

    Objects are centered on their x and y by default. Text is the exception and starts at its top-left corner.
  2. 2. How do you make one object always appear above another regardless of creation order?

    depth controls draw order; higher depth is drawn later and therefore on top.
  3. 3. Why is it a bad idea to draw with a Graphics object in update() without calling clear()?

    A Graphics object keeps all commands, so repeated drawing without clear() grows without bound.
  4. 4. Which color format do shape fills use, and which do text styles use?

    Shape and graphics methods take hexadecimal numbers. Text styles follow CSS so they take strings.

Summary

  • Shapes (rectangle, circle, star, polygon, line, arc, grid) are quick game objects that need no image files.
  • All game objects share position, scale, angle, alpha, depth, origin and visibility, and most setters chain.
  • The Graphics object draws free-form paths and fills; clear it or turn static drawings into textures.
  • Text objects take CSS-like styles, support wrapping, stroke and shadows; update them with setText and use bitmap text for heavy use.
  • Choose shapes for movable geometry, sprites for art and Graphics for static or debug drawings.

Next: Images and Sprites