Skip to main content
prepareWithSegments() is identical to prepare() but returns a richer handle that includes the segment text array. Use it when you need to render lines yourself — on canvas, SVG, WebGL, or server-side — via layoutWithLines(), walkLineRanges(), or layoutNextLine().
import { prepareWithSegments, layoutWithLines } from '@chenglou/pretext'

const prepared = prepareWithSegments('AGI 春天到了. بدأت الرحلة 🚀', '18px "Helvetica Neue"')
const { lines } = layoutWithLines(prepared, 320, 26)
for (let i = 0; i < lines.length; i++) ctx.fillText(lines[i].text, 0, i * 26)

Signature

prepareWithSegments(text: string, font: string, options?: PrepareOptions): PreparedTextWithSegments

Parameters

text
string
required
The text string to measure. Whitespace is normalized according to the whiteSpace option (defaults to CSS white-space: normal behavior).
font
string
required
CSS font shorthand in the same format as canvasContext.font. Must exactly match the CSS font declaration for the element being measured.Examples: "16px Inter", "bold 14px Arial", "italic 500 18px \"Helvetica Neue\"".
options
PrepareOptions
Optional configuration object. Same options as prepare().

Returns

PreparedTextWithSegments
object
Extends PreparedText with an additional segments field.

When to use

Use prepareWithSegments() instead of prepare() when:
  • You need the text content of each laid-out line (for canvas fillText, SVG <text>, etc.) — use with layoutWithLines().
  • You need per-line geometry without materializing strings (for shrinkwrap or binary-search layouts) — use with walkLineRanges().
  • You need variable per-line widths (for text flowing around floated images) — use with layoutNextLine().
If you only need the total height or line count, use prepare() + layout() instead. The opaque handle is cheaper to produce.
PreparedTextWithSegments is the unstable escape hatch for experiments and custom rendering. Its internal shape may change between releases.

Build docs developers (and LLMs) love