360 Secure SkillHub
360 安全技能中心

text-and-bitmaptext

面向 Phaser 4 开发者的文本渲染参考,讲解 Canvas Text 的样式、换行、分辨率与 Web Font 加载,以及 BitmapText、DynamicBitmapText 和 RetroFont 的用法与注意事项。

分类:开发
phaserjs
热度 0.00
最近更新 2026-12-03 17:40:34

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/text-and-bitmaptext
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
text-and-bitmaptext
description
Display text in Phaser 4: the Canvas-drawn Text object (this.add.text, TextStyle, fontFamily, fontSize, color, stroke, shadow, wordWrap, align, padding, fixedWidth, lineSpacing, letterSpacing, resolution, rtl), web fonts loaded with this.load.font, BitmapText and DynamicBitmapText (this.add.bitmapText, this.load.bitmapFont, setMaxWidth, setCharacterTint, setDropShadow, setDisplayCallback) and RetroFont. Use when showing a score, HUD, timer, damage numbers, dialogue box, title, menu label, button text or a custom font. Corrects old habits: Phaser can load web fonts itself, the font shorthand only takes one-word family names, setStyle merges rather than replaces, resolution 0 means 1. Triggers on: Text, BitmapText, this.add.text, font, web font, word wrap, text style, RetroFont.
metadata
{"phaser-version":"4.3.0"}

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.

  • font shorthand. 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; use fontFamily. For the same reason use setFontFamily(name), not setFont(name).
  • setStyle(style) merges into the current style. It ignores padding, lineSpacing and letterSpacing; use their setters.
  • Changing several things: each setter redraws. Pass them together to setStyle({ ... }) for one redraw. Don't assign font properties on text.style directly: updateText() alone doesn't rebuild the font string or metrics.
  • letterSpacing is slow. Any non-zero value draws one character at a time.
  • Resolution. resolution: 0 is treated as 1. Raise it (for example window.devicePixelRatio or 2) only when the text is scaled up or the Camera zooms in; it costs texture memory.
  • Right to left. Set rtl: true in the style. setRTL() after creation also swaps left and right alignment, but call updateText() 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 setTint and setCrop work 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 with this.load.xml and call Phaser.GameObjects.BitmapText.ParseFromAtlas(this, fontKey, atlasKey, frameName, xmlKey).
  • A wrong font key logs Invalid BitmapText key and then throws.
  • width and height are read-only, from the bounds. Size it with setFontSize or scale.
  • Since 4.3 BitmapText rounds its glyphs with roundPixels and vertexRoundMode like other objects, so it is no longer blurry at fractional positions when rounding is on.
  • setCharacterTint, setWordTint and setDropShadow are WebGL only and do nothing on DynamicBitmapText. A whole-object setTint works 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

  1. Origin is (0, 0) for Text and BitmapText, unlike Sprites. setOrigin(0.5) to center.
  2. align only affects multi-line text. To center one line, use setOrigin(0.5), or fixedWidth with align: 'center'.
  3. Fonts must be ready before the Text is made. Use this.load.font, or wait for CSS fonts.
  4. Updating Text every frame is expensive. Use BitmapText for values that change constantly.
  5. Text spacing is in pixels; BitmapText spacing is in font units. BitmapText lineSpacing and letterSpacing grow with fontSize.
  6. BitmapText setMaxWidth needs a wrap character. With no space (or the chosen char code) in a line, it doesn't wrap.