text-shape

Lays out text from a font file: shapes it, wraps it into lines, orders mixed left-to-right and right-to-left text, aligns it, and measures it. You get positioned glyphs and their outlines, and draw them however you like. Written in Rust, and also built for WebAssembly as an npm package.

Size
Layout
Style
show

Dashed: the layout box (maxWidth × maxHeight).
Shaded with a line: each line's advance box and baseline (together they make up fontBounds). Red: the tight ink bounds (textBounds).
Spacing is letter spacing in px. Kerning takes position:px pairs: 0:-4 puts 4px less space between the 1st and 2nd character, on top of the font's own kerning.

Features

JavaScript

npm install text-shape
import { loadFont, Typography, CENTER, TOP } from "text-shape";

const font = await loadFont("/fonts/Roboto-Regular.ttf");
const t = new Typography().textFont(font, 48).textAlign(CENTER, TOP);

// lines of positioned glyphs, wrapped to a 400 × 300 box at (50, 50)
const layout = t.layout("Hello world, wrapped in a box", 50, 50, 400, 300);

// draw with Canvas 2D: one cached Path2D per glyph, in font units
for (const line of layout.lines) {
  for (const g of line.glyphs) {
    if (!g.bbox) continue; // spaces
    ctx.save();
    ctx.translate(g.x, g.y);
    ctx.scale(layout.scale, layout.scale);
    ctx.fill(font.path(g.id, layout.variations));
    ctx.restore();
  }
}

t.textWidth("Hi"); // tight (ink) width, px
t.fontWidth("Hi"); // loose (advance) width, px
t.textBounds("Hi", 0, 0); // { x, y, w, h }

On npm as text-shape, with TypeScript types. It works in browsers and Node 20+ with no bundler setup: the WebAssembly is embedded in the package. Text positions (glyph clusters, line ranges) are UTF-16 offsets, so they work with String.slice.

Rust

[dependencies]
text-shape = "0.1"
use text_shape::{Font, HorizAlign, LayoutOptions};

let font = Font::from_bytes(std::fs::read("Roboto-Regular.ttf")?, 0)?;
let text = "Hello world, wrapped in a box";
let layout = font.layout(text, &LayoutOptions {
    size: 48.0,
    max_width: Some(400.0),
    align_h: HorizAlign::Center,
    ..Default::default()
})?;

for line in &layout.lines {
    println!("{:?}", &text[line.start..line.end]);
    for g in &line.glyphs {
        let outline = font.outline(g.id); // font units, y up
    }
}

On crates.io as text-shape, the same engine as the npm package. Rust 1.85+. Text positions are UTF-8 byte offsets.

JavaScript API

Typography setters are chainable; call them with no arguments to read the current value. Units are px with y down.

Function
loadFont(url), Font.fromBytes(bytes) Load a TTF, OTF or TTC font.
layout(str, x, y, maxWidth?, maxHeight?, extras?) Lines and positioned glyphs. Wraps when maxWidth is given; aligns within the box. extras.kerning, e.g. [{ at: 0, px: -4 }], adjusts specific character pairs.
textFont, textSize, textLeading Font, size and line height (default 1.25 × size).
textAlign(h, v?) START (default) END LEFT CENTER RIGHT × TOP CENTER BOTTOM BASELINE (default). START and END follow the text direction, like CSS text-align.
textWrap(mode) WORD or CHAR
textDirection(dir) "ltr", "rtl" or "inherit" (detect)
textWeight(n), textStyle(style) Weight, and NORMAL ITALIC BOLD BOLDITALIC. Uses the font's axes when it has them (bold means a weight of at least 700); otherwise layout().synthetic says how to fake bold and italic.
textProperty(name, value?) fontKerning, fontVariantCaps, letterSpacing, wordSpacing, direction, fontFeatures, fontVariationSettings
fontWidth, fontBounds Loose (advance-based) width and box.
textWidth, textBounds Tight (ink) width and box.
fontAscent, fontDescent, textAscent, textDescent From the font's metrics, or tight for a given string.
The measurements that take a string accept the same optional extras as layout(), as their last argument, e.g. t.textWidth("AVATAR", { kerning }).
font.path(id), font.outline(id) A glyph as a cached Path2D, or as path commands.