Text2D

Text inside a 2D scene — a sign in the world, a map label, a nameplate over a character, a damage number: a Node2D that moves and sorts with the sprites. Font2D is the font it draws with, loaded once. Text over the game that stays put while the camera moves (a score, a pause menu) is UI — UIText among the scene's widgets.

  • write text in the 2D game world: a sign, a label, a damage number
  • label a place on a 2D map with text that keeps its size on screen
  • show a name over a character that follows it
  • load a font for 2D text, and its bold weight
  • wrap a 2D text at a width and cap it at a few lines
  • put an outline around text so it reads over any background
  • measure a text block to put a panel behind it
  • center or right-align the lines of a text

Platforms: wherever a Scene2D runs; headless tests lay a text out (bounds) but draw nothing.

At a glance

TypeScript
const inter = font("inter")                 // compile time: installs Inter (400 / 500 / 700), returns "Inter"

const main = async () => {
  const scene = new Scene2D({ background: "#10131a" })
  const regular = await Font2D.load(inter)
  const bold = await Font2D.load(inter, { weight: 700 })

  const title = new Text2D({ font: bold, text: "Level 1", fontSize: 32, position: [0, 120] })
  const sign = new Text2D({
    font: regular, text: "Old mill", fontSize: 14, units: "px",   // 14 logical px on screen, always
    anchor: [0.5, 1], position: [-80, 0], outline: { width: 0.12, color: "#000" },
  })
  scene.add(title, sign)
  scene.open()
}
main()

Load the font of a Text2D, once for every size: Font2D.load

TypeScript
Font2D.load(source: string | FetchResponse | File, options?: {
  weight?: number      // a registered family: the face's weight; default 400, else the nearest registered
  italic?: boolean     // a registered family: the italic face; default false
}): Promise<Font2D>

font.destroy(): void   // free the font and its atlas, for every holder

source is a family the font() macro installed — font("inter") compiles to "Inter" — or a TTF / OTF file: asset('./fonts/Brand.ttf'), a URL, a fetched response, a File the user chose. A family resolves to its face's TTF (the same faces UI text uses), the exact weight or the nearest one installed; a family nobody installed rejects with the list of installed ones. A source with a /, . or : is a file and is fetched as is.

Load a font once and use it at every size: a load by family or by URL is cached, so every Font2D.load("Inter") of a project shares one native font. destroy() frees it for every holder (texts still using it stop drawing); a later load parses it again.

TypeScript
const main = async () => {
  const brand = await Font2D.load(asset("./fonts/Brand.ttf"))     // a font file of the project
  const scene = new Scene2D()
  scene.add(new Text2D({ font: brand, text: "Brand", fontSize: 40 }))
  scene.open()
}
main()
Note

every font has one SDF glyph atlas of its own, 2048 × 2048 (16 MB on the CPU, as much on the GPU), made at its first glyph: about 1400 glyphs of Inter — a font's Latin, Cyrillic and Greek with room to spare. When it is full the engine logs glyph atlas full and further glyphs draw as nothing; a CJK-sized set needs a second font file.

Create a text: new Text2D

TypeScript
new Text2D(options: {
  font: Font2D
  text: string                     // '\n' breaks a line
  fontSize?: number                // the em, in `units`; default 16
  units?: 'world' | 'px'           // default 'world'; 'px' = logical screen px at any zoom
  color?: ColorInput               // default white; its alpha counts
  align?: 'left' | 'center' | 'right'   // the lines inside the block; default 'left'
  maxWidth?: number                // wrap width, in the node's units; omit = no wrap
  maxLines?: number                // cap at N lines; 0 / omit = unlimited
  overflow?: 'ellipsis' | 'clip'   // how a capped block's last line ends; default 'ellipsis'
  lineHeight?: number              // multiplier of the font's own line height; default the font's
  letterSpacing?: number           // extra space after each letter, in em; default 0
  outline?: { width: number, color?: ColorInput }   // a halo, width in em; color default black
  anchor?: Vec2Like                // block pivot: [0,0] top-left … [1,1] bottom-right; default [0.5, 0.5]
  position?: Vec2Like
  rotation?: number                // degrees, CCW
  scale?: number | Vec2Like
  z?: number                       // draw order, see Scene2D
  renderPriority?: number          // 0..7, default 4
  material?: Material2D            // only its blend matters for a text
})

Every option is a live property of the same name (label.text = 'Score 3', label.outline = null). A write of text, font, fontSize, units or a layout option lays the block out again natively, once — never per frame: when a text only moves, animate the node's transform, not its text. Scope: Latin, Cyrillic, Greek-style scripts with kerning; no complex shaping (Arabic, Indic) and no emoji — UIText has those.

How big a 2D text is: fontSize and units

fontSize is the em, as UIText and Canvas size it: a 16 px Text2D is as big as a 16 px UIText. One line is the font's own line pitch tall (1.21 × fontSize for Inter).

  • units: 'world' (the default) — world units: the text is part of the world and scales with it on screen. Its glyphs are distance fields, so the edges stay sharp at any scale.
  • units: 'px' — logical screen px: the same size on screen at every scale of the world, like a map label or a nameplate. Drawn unrotated, it lands on the device-pixel grid and reads like UI text.

A node scale scales either.

Label a place on a map: units: 'px' and outline

A map label keeps its size on screen (units: 'px') and an outline keeps it readable over any background. outline.width is in em: 0.05 is thin, 0.15 the most.

TypeScript
const main = async () => {
  const scene = new Scene2D({ background: "#d8d2c4" })
  const inter = await Font2D.load(font("inter"))
  const label = new Text2D({
    font: inter, text: "Moscow", fontSize: 13, units: "px",
    anchor: [0.5, 1], position: [120, 40],                // the bottom center sits on the place
    color: "#222", outline: { width: 0.12, color: "#fff" },
  })
  scene.add(label)
  scene.open()
  scene.camera.zoom = 4                                    // 4× closer: the label stays 13 px
}
main()

The outline is drawn in the pass under every body of the same renderPriority and z (draw order): two labels that overlap never have a halo over the other's letters.

A name over a character: parent the text

A nameplate is a child of the character: it follows it, and joins its scene with it.

TypeScript
const main = async () => {
  const scene = new Scene2D()
  const inter = await Font2D.load(font("inter"))
  const hero = new Sprite({ size: [24, 40], color: "#4f7cff", anchor: [0.5, 1] })
  const name = new Text2D({
    font: inter, text: "Ada", fontSize: 12, units: "px",
    anchor: [0.5, 1], position: [0, 46], outline: { width: 0.12 },
  })
  hero.add(name)                                // follows the hero, in the hero's scene
  scene.add(hero)
  scene.open()
  hero.animateTo({ x: 160, duration: 1500 })   // the name goes along
}
main()

Wrap a 2D text at a width and cap its lines: maxWidth, maxLines, overflow

TypeScript
text.maxWidth = 220          // wrap width in the node's units: world, or logical px with units 'px'
text.maxLines = 2            // keep the first 2 lines (UIText's lineClamp); 0 = unlimited
text.overflow = 'ellipsis'   // or 'clip' (UIText's textOverflow)

maxWidth and bounds are in the node's units — world units, or logical px with units: 'px' — not in multiples of fontSize. Lines break at \n and wrap greedily at spaces; a word longer than the width stays whole and sticks out. With maxLines, the last kept line of a longer block ends in "…" (U+2026; three periods in a font without it), trimmed by whole characters until it fits maxWidth — without a maxWidth the ellipsis just lengthens it; 'clip' cuts the block after the last kept line as it is.

Measure a text: bounds

TypeScript
text.bounds: Vec2   // [width, height] of the laid-out block, after wrap and the line cap

In the node's units (world, or logical px with units: 'px'), without the node's scale. Read it to size a panel or a button behind the text:

TypeScript
const main = async () => {
  const scene = new Scene2D({ background: "#10131a" })
  const inter = await Font2D.load(font("inter"))
  const quest = new Text2D({
    font: inter, fontSize: 16, maxWidth: 220, maxLines: 2, align: "center",
    text: "Find the old mill north of the river and bring back the miller's key",
  })
  const size = quest.bounds                                                   // two lines, at most 220 wide
  const panel = new Sprite({ size: [size.x + 24, size.y + 16], color: "#223" })
  panel.z = -1                                                                // under the text
  scene.add(panel, quest)                                                     // both centered on the origin
  scene.open()
}
main()

Lines, letters and the block's pivot: align, lineHeight, letterSpacing, anchor

  • align places each line inside the block ('left', 'center', 'right').
  • lineHeight multiplies the font's own line pitch (1.5 = half as much again); it is not a length.
  • letterSpacing is extra space after every letter in em, so it scales with fontSize (0.05 at fontSize 20 = 1 unit).
  • anchor is the point of the block that sits on the node's position, in the sprite's Y-down anchor space: [0.5, 1] = bottom center, [0, 0] = top-left.

Text in a scene file: the text block

TypeScript
// title.scene2d.ts
export default defineScene2d({
  nodes: {
    sign: { text: { font: font("inter"), text: "Forest", fontSize: 14, units: "px" }, position: [0, 64] },
  },
})

font is a string here: a family font() installed, or a font file (asset('./fonts/Brand.ttf')), loaded with Font2D.load at its regular face; the other keys are the options above, and the node's color prop sets the color too. See scene files.

Pitfalls

TypeScript
// ✗ measuring maxWidth in characters or ems
new Text2D({ font, text, fontSize: 20, maxWidth: 12 })    // 12 world units: one word per line
// ✓ the width in the node's units
new Text2D({ font, text, fontSize: 20, maxWidth: 240 })

// ✗ a HUD score as a Text2D: it moves and scales with the world
// ✓ UIText in the scene's widgets: scene.widgets(UIWidget(UIText(() => `Score: ${score.value}`)))

See also

  • Scene2D — draw order, the HUD over the scene
  • Node2D — transform, hierarchy (inherited)
  • Fonts — the font() macro: families, weights, your own font file
  • Path2D — lines and shapes beside the text
  • Camera2D — zoom