Files
skills/docs/media/fonts/font-convert/src/utils/outline-to-string.md
2026-05-29 08:20:56 +01:00

2.9 KiB

outlineToString

Purpose

Serialises an array of PathCommand objects to the space-separated token string stored in a TypefaceGlyph's o field. The typeface.js format requires each command to be written as "type [x y] [x1 y1] [x2 y2]" with a trailing space after each coordinate group. outlineToString encapsulates this serialisation contract and applies an optional scale factor so that internal font-unit coordinates are normalised to the 1 000-unit resolution expected by Three.js FontLoader.

Features

  • Handles all five typeface.js command types: m, l, q, b, z
  • Emits only the coordinate fields present on each command
  • Applies a floating-point scale multiplier and rounds each coordinate to the nearest integer
  • Returns an empty string for an empty command array
  • Does not mutate the input array

Usage: Basic Example

import { outlineToString } from "@suaveplan/font-convert";
import type { PathCommand } from "@suaveplan/font-convert";

const commands: PathCommand[] = [
  { type: "m", x: 0,   y: 0 },
  { type: "l", x: 100, y: 0 },
  { type: "z" },
];

const outline = outlineToString(commands);
// → "m 0 0 l 100 0 z "

Usage: Advanced Example

import { outlineToString } from "@suaveplan/font-convert";
import type { PathCommand } from "@suaveplan/font-convert";

// Apply a scale factor when coordinates are in raw font units
const unitsPerEm = 1000;
const scale = (1000 * 100) / (unitsPerEm * 72); // ≈ 1.389

const commands: PathCommand[] = [
  { type: "m",  x: 0,   y: 0 },
  { type: "q",  x1: 360, y1: 720, x: 720, y: 0 },
  { type: "b",  x1: 100, y1: 200, x2: 300, y2: 400, x: 1000, y: 0 },
];

const outline = outlineToString(commands, scale);
// coordinates are Math.round(value * scale)

API Reference

outlineToString(commands: PathCommand[], scale?: number): string

Parameter Type Default Description
commands PathCommand[] — Path commands to serialise
scale number 1 Multiplier applied to all coordinate values before rounding

Returns: The typeface.js outline string. Each command contributes one token group ending with a trailing space. Returns "" when commands is empty.

Coordinate order per command type:

Type Token sequence
m m x y
l l x y
z z
q q x y x1 y1
b b x y x1 y1 x2 y2

Implementation Notes

The coordinate emission order matches what FontConverter and the reference typeface.js CLI produce: the endpoint x/y is written before control points x1/y1 and x2/y2. This is the order required by the Three.js FontLoader parser. Changing this order would silently corrupt all outlines that use bezier curves.

The scale factor default of 1 makes outlineToString directly testable with integer coordinates without requiring the caller to know the actual font resolution.