Pretext.js Tutorial: Getting Started

A step-by-step pretext.js tutorial — install pretext, run your first DOM-free text measurement, and render wrapped lines yourself, in under 10 minutes.

Pretext is a zero-dependency JavaScript/TypeScript library for multiline text measurement and layout by Cheng Lou. It computes line breaks, line count, and pixel height with pure arithmetic — no DOM reads, no layout thrashing. This tutorial walks through:

  1. Install — npm install @chenglou/pretext, or import the ES module from a CDN with a script tag (no bundler needed).
  2. Load fonts first — await document.fonts.ready before measuring, so glyph widths aren't cached from the fallback font.
  3. First measurement — prepare('Hello, world!', '16px Inter') then layout(prepared, 200, 24) returns { lineCount: 1, height: 24 }; the same prepared text at 60px wide returns { lineCount: 2, height: 48 }.
  4. Render wrapped lines — prepareWithSegments() + layoutWithLines() give you each line's text and pixel width, ready to render as elements or draw on canvas.
  5. Where next — the Accordion, Balanced Text, Virtualized Lists, and Canvas Rendering demos, plus the API reference.

This page is part of Learn Pretext — interactive tutorials and live demos for pretext.js, the zero-dependency JavaScript text measurement library by Cheng Lou. Read why pretext exists, or browse the API reference. Enable JavaScript to run the tutorial's live examples and interactive sandbox.