OpenType.js

1.3.4 · maintenance · verified Tue Apr 21

OpenType.js is a JavaScript library designed for parsing and writing TrueType and OpenType fonts, providing deep access to font data and glyph outlines. The current stable version on npm is 1.3.4, released in 2021, though active development continues on the `master` branch with many bug fixes and new features awaiting a 2.0.0 release. It supports a wide range of font formats including WOFF, OTF, and TTF (both TrueType `glyf` and PostScript `cff` outlines). Key differentiators include its ability to create Bezier paths from text, handle composite glyphs, kerning (GPOS/kern table), ligatures, and TrueType font hinting. It runs seamlessly in both browser environments and Node.js, offering a low memory mode option for efficiency.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates asynchronous font loading from a URL and rendering text into a scalable vector path using the `getPath` method. Includes a mock canvas context for logging drawing operations.

import opentype from 'opentype.js';

// Simulate a canvas environment for Node.js or ensure this runs in a browser.
// In a browser, getContext('2d') would work directly on a <canvas> element.
// For Node.js, a library like 'canvas' would be needed.

// Mocking a canvas context for demonstration purposes
const mockCanvasContext = {
  beginPath: () => console.log('beginPath'),
  moveTo: (x, y) => console.log(`moveTo(${x}, ${y})`),
  lineTo: (x, y) => console.log(`lineTo(${x}, ${y})`),
  quadraticCurveTo: (cx, cy, x, y) => console.log(`quadraticCurveTo(${cx}, ${cy}, ${x}, ${y})`),
  bezierCurveTo: (c1x, c1y, c2x, c2y, x, y) => console.log(`bezierCurveTo(${c1x}, ${c1y}, ${c2x}, ${c2y}, ${x}, ${y})`),
  closePath: () => console.log('closePath'),
  fill: () => console.log('fill'),
  stroke: () => console.log('stroke')
};

async function loadAndDrawFont() {
  try {
    // Replace with a real font URL or path.
    // For a local file in Node.js, you'd use fs.readFileSync and opentype.parse.
    // For browser, 'fonts/Roboto-Black.ttf' would be relative to the HTML.
    const font = await opentype.load('https://raw.githubusercontent.com/opentypejs/opentype.js/master/fonts/Roboto-Black.ttf');
    console.log('Font loaded successfully.');

    const text = 'Hello, World!';
    const fontSize = 72;
    const x = 0;
    const y = 150;

    // Construct a Path object containing the letter shapes
    const path = font.getPath(text, x, y, fontSize);
    console.log(`Generated path for text: "${text}"`);

    // To draw on a real canvas:
    // const ctx = document.getElementById('myCanvas').getContext('2d');
    // path.draw(ctx);

    // Using the mock context to show operations:
    path.draw(mockCanvasContext);
    console.log('Path drawing operations logged.');
  } catch (err) {
    console.error('Error loading or drawing font:', err);
  }
}

loadAndDrawFont();

view raw JSON →