Text and BitmapText
The Text object draws with the Canvas 2D API into its own texture. BitmapText draws glyphs from a font texture and batches like sprites.
Source: src/gameobjects/text/Text.js, src/gameobjects/text/TextStyle.js, src/gameobjects/bitmaptext/static/BitmapText.js, src/gameobjects/bitmaptext/dynamic/DynamicBitmapText.js, src/gameobjects/bitmaptext/ParseRetroFont.js, src/loader/filetypes/FontFile.js. Related: loading-assets, game-object-components, sprites-and-images.
Quick start
preload ()
{
this.load.font('Nokia', 'assets/fonts/nokia.ttf', 'truetype'); // key = the family name to use
this.load.bitmapFont('arcade', 'assets/fonts/arcade.png', 'assets/fonts/arcade.xml');
}
create ()
{
const title = this.add.text(this.scale.width / 2, 80, 'My Game', {
fontFamily: 'Nokia',
fontSize: 48, // a number becomes '48px'
color: '#ffffff',
stroke: '#000000',
strokeThickness: 6
}).setOrigin(0.5); // Text and BitmapText default to origin (0, 0)
const score = this.add.bitmapText(16, 16, 'arcade', 'SCORE 0', 24);
score.setText('SCORE 100'); // cheap: no canvas redraw
}
Text or BitmapText?
- Text: any CSS or web font, stroke, shadow, gradients, word wrap, RTL. Every change redraws its canvas and uploads a new texture, so avoid changing it every frame.
- BitmapText: fast and batched, good for scores, timers, damage numbers and lots of labels. The look is fixed by the font texture. Wraps with
setMaxWidth. - DynamicBitmapText: BitmapText plus a per-character callback each frame and a scrolling crop. Slower; only for per-letter effects.
Web fonts
this.load.font(key, url, format = 'truetype', descriptors) loads the file with the FontFace API and adds it to document.fonts. Use the key as the fontFamily. It is ready in create. A font that fails only logs a console warning, and the Text falls back to another font. Details and the config form: loading-assets.
this.load.font('Display', 'assets/fonts/display-bold.woff2', 'woff2', { weight: '700' });
// later: { fontFamily: 'Display', fontStyle: 'bold' }
A font from CSS @font-face or a font service is loaded lazily by the browser. A Text created before it arrives is drawn and measured with a fallback font and won't fix itself. Wait for it first, for example await document.fonts.load('32px "My Font"') before starting the Scene, or load it with this.load.font.
Text style
const label = this.add.text(100, 100, 'Hello', {
fontFamily: 'Georgia, "Goudy Bookletter 1911", serif', // quote names with spaces or digits
fontSize: '24px',
fontStyle: 'bold italic',
color: '#ffcc00', // `fill` is an alias
stroke: '#000', strokeThickness: 4,
backgroundColor: '#222244',
shadow: { offsetX: 2, offsetY: 2, color: '#000', blur: 4, fill: true, stroke: false },
align: 'center', // 'left' | 'right' | 'center' | 'justify'; multi-line only
padding: { x: 10, y: 6 }, // or { left, right, top, bottom }
lineSpacing: 4,
letterSpacing: 1,
wordWrap: { width: 300, useAdvancedWrap: true },
fixedWidth: 320, // 0 = fit the text
maxLines: 3,
resolution: 2
});
Defaults: fontFamily: 'Courier', fontSize: '16px', color: '#fff', strokeThickness: 0, align: 'left', resolution: 1.
Setters, all chainable: setText, appendText(text, addCR = true), setFontFamily, setFontSize, setFontStyle, setColor / setFill, setStroke(color, thickness), setShadow(x, y, color, blur, stroke, fill), setBackgroundColor, setAlign, setWordWrapWidth(width, useAdvancedWrap), setWordWrapCallback(fn, scope), setFixedSize(w, h), setPadding(...), setMaxLines, setLineSpacing, setLetterSpacing, setResolution, setRTL. getWrappedText() returns the wrapped lines.
fontshorthand.font: '[style] size family', split on spaces, so the family must be one word:font: 'bold 24px Arial'. A family with spaces or quotes ('"Press Start 2P"') breaks it; usefontFamily. For the same reason usesetFontFamily(name), notsetFont(name).setStyle(style)merges into the current style. It ignorespadding,lineSpacingandletterSpacing; use their setters.- Changing several things: each setter redraws. Pass them together to
setStyle({ ... })for one redraw. Don't assign font properties ontext.styledirectly:updateText()alone doesn't rebuild the font string or metrics. letterSpacingis slow. Any non-zero value draws one character at a time.- Resolution.
resolution: 0is treated as 1. Raise it (for examplewindow.devicePixelRatioor 2) only when the text is scaled up or the Camera zooms in; it costs texture memory. - Right to left. Set
rtl: truein the style.setRTL()after creation also swaps left and right alignment, but callupdateText()after it. - Gradient fill: create it on the text's own context, then
setFill:
const t = this.add.text(100, 300, 'GOLD', { fontFamily: 'Arial', fontSize: 64 });
const gradient = t.context.createLinearGradient(0, 0, 0, t.height);
gradient.addColorStop(0, '#fff6a0');
gradient.addColorStop(1, '#c58a00');
t.setFill(gradient);
- Text has the Tint (WebGL) and Crop components, so
setTintandsetCropwork on it. - For crisp text, keep its origin at 0 and its position on whole pixels, or enable
roundPixels.
BitmapText
// bitmapText(x, y, fontKey, text, size, align)
const t = this.add.bitmapText(100, 100, 'arcade', 'Line one\nLine two', 32, Phaser.GameObjects.BitmapText.ALIGN_CENTER);
t.setText('NEW TEXT'); // or t.text = ...
t.setFontSize(48);
t.setLetterSpacing(2); // added after kerning; in the font's own units
t.setLineSpacing(4); // font units too: both scale by fontSize / the font's size
t.setMaxWidth(300); // wraps on spaces (char code 32); setMaxWidth(300, 45) wraps on '-'
t.setCenterAlign(); // setLeftAlign / setRightAlign; align: 0, 1, 2
t.setDropShadow(2, 2, 0x000000, 0.5); // WebGL only, static BitmapText only; setDropShadow() removes
t.setCharacterTint(0, 4, Phaser.TintModes.MULTIPLY, 0xff0000); // start, length (-1 = to end), mode, colors
t.setWordTint('TEXT', -1, Phaser.TintModes.MULTIPLY, 0x00ff00); // word or index, count (-1 = all), mode, colors
const bounds = t.getTextBounds(); // { local, global, lines: { shortest, longest, height, lengths }, words, characters, wrappedText, ... }
- Load the font with
this.load.bitmapFont(key, textureURL, fontDataURL). The data must be BMFont XML. For a font packed in an atlas, load the XML withthis.load.xmland callPhaser.GameObjects.BitmapText.ParseFromAtlas(this, fontKey, atlasKey, frameName, xmlKey). - A wrong font key logs
Invalid BitmapText keyand then throws. widthandheightare read-only, from the bounds. Size it withsetFontSizeor scale.- Since 4.3 BitmapText rounds its glyphs with
roundPixelsandvertexRoundModelike other objects, so it is no longer blurry at fractional positions when rounding is on. setCharacterTint,setWordTintandsetDropShadoware WebGL only and do nothing on DynamicBitmapText. A whole-objectsetTintworks on both (WebGL only).
DynamicBitmapText
const wavy = this.add.dynamicBitmapText(100, 200, 'arcade', 'WAVY TEXT', 32);
wavy.setDisplayCallback((data) =>
{
// data: parent, tint, tintMode, index, charCode, x, y, scale, rotation, data
data.y += Math.sin(data.index * 0.5 + this.time.now * 0.005) * 8;
return data; // must return it
});
wavy.setSize(200, 40); // crop window in pixels
wavy.setScrollX(10); // scroll the text inside the window
Since 4.3 DynamicBitmapText draws lineSpacing, so multi-line text matches a BitmapText with the same settings.
RetroFont
A fixed-width font from a grid of characters in an ordinary image.
// preload: this.load.image('knight', 'assets/fonts/knight3.png');
const config = {
image: 'knight',
width: 31,
height: 25,
chars: Phaser.GameObjects.RetroFont.TEXT_SET6,
charsPerRow: 10,
spacing: { x: 1, y: 1 },
offset: { x: 0, y: 0 }
};
this.cache.bitmapFont.add('knight', Phaser.GameObjects.RetroFont.Parse(this, config)); // Parse returns the cache entry
this.add.bitmapText(100, 100, 'knight', 'PHASER');
TEXT_SET1 to TEXT_SET11 in src/gameobjects/bitmaptext/const.js give the common character orders.
Gotchas
- Origin is (0, 0) for Text and BitmapText, unlike Sprites.
setOrigin(0.5)to center. alignonly affects multi-line text. To center one line, usesetOrigin(0.5), orfixedWidthwithalign: 'center'.- Fonts must be ready before the Text is made. Use
this.load.font, or wait for CSS fonts. - Updating Text every frame is expensive. Use BitmapText for values that change constantly.
- Text spacing is in pixels; BitmapText spacing is in font units. BitmapText
lineSpacingandletterSpacinggrow withfontSize. - BitmapText
setMaxWidthneeds a wrap character. With no space (or the chosen char code) in a line, it doesn't wrap.
