Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Audio and UI

Text and Buttons

Style text in Phaser with fonts, strokes, shadows and word wrap, then build reusable buttons, toggles and sliders with interactive containers.

Every game needs words and clickable things: a title, a score, a "Play" button, a volume slider. Phaser has no HTML form controls built in for the canvas, so game user interfaces are made from the same game objects you already know: text, rectangles, images and containers, made interactive with pointer events. That is a good thing, because these controls scale with the game, work with the camera and tweens, and look the same on every device.

This lesson covers the Text object and its style options, the difference with bitmap text, and then builds three controls you can reuse in any project: a button with hover and pressed states, an on/off toggle and a slider you can drag.

The Text game object

this.add.text(x, y, content, style) creates a text object. Phaser draws the text to a hidden canvas and uses that canvas as a texture, so you can style it with the same options as CSS-like canvas text:

JavaScript
const title = this.add.text(240, 40, 'Space Rescue', {
  fontFamily: 'Georgia, serif',
  fontSize: '40px',
  fontStyle: 'bold',
  color: '#fde68a',
  stroke: '#7c2d12',
  strokeThickness: 6,
  align: 'center',
  shadow: { offsetX: 3, offsetY: 3, color: '#000000', blur: 4, fill: true }
}).setOrigin(0.5);

The most useful style options:

Option Meaning
fontFamily, fontSize, fontStyle The font; size needs a unit such as '24px'
color Fill color as a CSS string; fill is the same thing
stroke, strokeThickness An outline
backgroundColor, padding A filled box behind the text; padding is { x, y } or { left, right, top, bottom }
align left, center or right for multi-line text
wordWrap { width: 300, useAdvancedWrap: true } wraps long text
lineSpacing Extra pixels between lines
fixedWidth, fixedHeight Force the text box size
shadow A drop shadow
resolution Render at a higher resolution for sharper text on high-density screens

After creation you change the text with setText('Score: 10'), and the style with methods such as setColor, setStroke, setFontSize, setWordWrapWidth and setShadow. Text with setOrigin(0.5) is centered on its position, which is the easiest way to center a label inside a button.

Text styles

Because text is a game object, tweens, tints, rotation, scale, depth, camera scroll factors and masks all work on it.

Fonts

By default, text uses fonts that the browser already has. For a custom font you have to be careful: a web font loads asynchronously, and text drawn before the font is ready uses a fallback and does not update itself later. Two common solutions:

  1. Load the font with CSS @font-face and wait for document.fonts.load('24px "My Font"') to resolve before starting the game or the scene.
  2. Use bitmap text.

Bitmap text (this.add.bitmapText(x, y, 'fontKey', 'Hello')) draws characters from a texture atlas that you load together with an XML or JSON font description (this.load.bitmapFont('fontKey', 'font.png', 'font.xml')). It is crisper for pixel art, faster when you change text every frame (a score), and not affected by the browser's font loading. You create the font files with tools such as Littera or Hiero, so we show it as a read-only snippet here:

JavaScript
preload() {
  this.load.bitmapFont('arcade', 'assets/arcade.png', 'assets/arcade.xml');
}
create() {
  this.score = this.add.bitmapText(16, 16, 'arcade', 'SCORE 0', 16);
}
// later
this.score.setText('SCORE ' + points);

Use ordinary Text for menus, dialogue and anything that needs many different sizes, and bitmap text for score displays and retro games.

A reusable button

A button needs a background, a label, and reactions for four moments: the pointer is over it, leaves it, presses it, and releases it. The cleanest way is a container that holds the pieces, with a hit area set by setSize. You write the code once as a function and use it everywhere:

JavaScript
function makeButton(scene, x, y, label, onClick) {
  const bg = scene.add.rectangle(0, 0, 160, 44, 0x2563eb).setStrokeStyle(2, 0xffffff);
  const text = scene.add.text(0, 0, label, { fontSize: '18px', color: '#fff' }).setOrigin(0.5);
  const button = scene.add.container(x, y, [bg, text]);
  button.setSize(160, 44).setInteractive({ useHandCursor: true });
  button.on('pointerover', () => bg.setFillStyle(0x3b82f6));
  button.on('pointerout', () => bg.setFillStyle(0x2563eb));
  button.on('pointerdown', () => button.setScale(0.96));
  button.on('pointerup', () => { button.setScale(1); onClick(); });
  return button;
}

Two details matter. The container's hit area is a rectangle centered on its position (because the container has no origin of its own, setSize makes the area symmetric around x, y). And the click should fire on pointerup, not pointerdown, so that the player can drag away from a button to cancel, as in every desktop and mobile app. Note also pointerupoutside: reset the pressed look there too.

Toggles and sliders

A toggle is a button that remembers a boolean. A slider is a draggable handle whose position is converted into a value between a minimum and a maximum. Phaser has a built-in drag system: make an object interactive, call this.input.setDraggable(object), and listen for the drag event, which gives you the new position.

Buttons, toggle and slider

The slider's drag event gives dragX, the pointer-adjusted x position, and the code clamps it to the track. The same pattern drives volume sliders, color pickers and scroll bars.

Input details worth knowing

  • Hit areas. Shapes such as rectangles and circles made with this.add.rectangle are interactive in their real shape. For images and text the hit area is the bounding box; pass a different shape to setInteractive(new Phaser.Geom.Rectangle(...), Phaser.Geom.Rectangle.Contains) when you want a smaller or larger target. For touch screens make buttons at least 44 by 44 pixels.
  • Top-most only. By default a click only reaches the top object under the pointer. this.input.topOnly = false lets overlapping objects all receive it.
  • Disabling. button.disableInteractive() and button.setInteractive() turn a control off and on. Also change its look (gray it out) so the player understands.
  • Keyboard. The canvas controls do not receive focus like HTML buttons. If keyboard play matters, add key handlers (Enter to activate the selected button) and a visible selected state. Players using screen readers cannot use canvas-only menus, so offer an HTML alternative for critical flows (settings in a normal page, for example).
  • Phaser DOM elements. this.add.dom(x, y, 'input') places real HTML elements, with dom: { createContainer: true } in the game config. That is the way to get a text field for names or chat. They sit above the canvas and do not go through the camera zoom.

Common mistakes

  • Creating text every frame in update(). Create it once and call setText, because each new text allocates a canvas.
  • Forgetting the unit in fontSize (16 instead of '16px').
  • Using pointerdown for clicks, which prevents drag-away cancel and triggers actions when a touch is meant as a scroll.
  • Calling setInteractive on a container without calling setSize first. The container has no size, so nothing is clickable.
  • Blurry text on high-density screens; set resolution: window.devicePixelRatio in the text style or enable pixelArt only for bitmap fonts.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a container the usual base for a button?

    A container holds several game objects and acts as a single unit. With setSize and setInteractive, the whole group becomes one clickable button.
  2. 2. Which pointer event should trigger a button's action, and why?

    Firing on release matches desktop and mobile conventions and avoids accidental activations.
  3. 3. What is a good reason to choose bitmap text over regular text?

    Bitmap fonts are drawn from a texture atlas, so updating a score every frame is cheap and the look is the same everywhere.
  4. 4. You call setInteractive() on a new container but clicks do nothing. What is the most likely cause?

    A container does not measure its children. Give it a width and height with setSize so Phaser can test the pointer against it.

Summary

  • this.add.text creates a styled text object; update it with setText instead of creating new ones.
  • Wait for web fonts to load, or use bitmap text for crisp, fast, loader-independent text.
  • A button is a container of background and label with hover, press and release states; fire the action on pointerup.
  • Toggles keep a boolean; sliders use setDraggable and the drag event, then clamp and convert the position to a value.
  • Make touch targets big, mind keyboard and accessibility needs, and use DOM elements for real text inputs.

Next: HUDs, Menus and Pause Screens