For advanced use cases like Canvas, SVG, or WebGL rendering, use the prepareWithSegments and manual layout APIs. This allows you to control exactly how and where lines are drawn.
Key APIs:
prepareWithSegments(text, font, options): Returns a PreparedTextWithSegments handle.layoutWithLines(prepared, maxWidth, lineHeight): Returns an array of LayoutLine objects containing text and dimensions.measureLineStats(prepared, maxWidth): Returns { lineCount, maxLineWidth } without allocating strings, useful for 'shrink-wrap' container calculations.walkLineRanges(prepared, maxWidth, callback): Iterates through lines by calling a callback with LayoutLineRange (width and cursors) for each line.layoutNextLineRange(prepared, cursor, maxWidth): An iterator-like API for variable-width layouts (e.g., flowing text around an image). Returns a LayoutLineRange or null when exhausted.materializeLineRange(prepared, range): Converts a LayoutLineRange into a full LayoutLine containing the actual text string.
import { prepareWithSegments, layoutWithLines } from '@chenglou/pretext'
const prepared = prepareWithSegments('AGI 春天到了. بدأت الرحلة 🚀', '18px "Helvetica Neue"')
const { lines } = layoutWithLines(prepared, 320, 26) // 320px max width, 26px line height
for (let i = 0; i < lines.length; i++) ctx.fillText(lines[i].text, 0, i * 26)