Home

Awesome

<div align="center"> <h1>opentype.js</h1> <a href="https://www.npmjs.com/package/opentype.js"><img alt="Latest version on npm" src="https://img.shields.io/npm/v/opentype.js.svg?style=flat" /></a> <a href="https://www.npmjs.com/package/opentype.js"><img alt="npm downloads, yearly" src="https://img.shields.io/npm/dy/opentype.js.svg?style=flat" /></a> <a href="https://github.com/opentypejs/opentype.js/blob/master/LICENSE"><img alt="MIT License" src="https://img.shields.io/github/license/opentypejs/opentype.js" /></a> <a href="https://github.com/opentypejs/opentype.js/actions/workflows/ci.yml?query=branch%3Amaster"><img alt="GitHub Workflow Status (with event)" src="https://img.shields.io/github/actions/workflow/status/opentypejs/opentype.js/ci.yml"></a> <br /><br /> </div>

It gives you access to the letterforms of text from the browser or Node.js.

See https://opentype.js.org/ for a live demo.

Features

Installation

via CDN

Select one of the following sources in the next example:

<!-- using global declaration -->
<script src="https://your.favorite.cdn/opentype.js"></script>
<script>opentype.parse(...)</script>

<!-- using module declaration (need full path) -->
<script type=module>
import { parse } from "https://unpkg.com/opentype.js/dist/opentype.mjs";
parse(...);
</script>

via npm package manager

npm install opentype.js
const opentype = require('opentype.js');

import opentype from 'opentype.js'

import { load } from 'opentype.js'

Using TypeScript? See this example

Contribute

If you plan on improving or debugging opentype.js, you can:

Usage

Loading a WOFF/OTF/TTF font

This is done in two steps: first, we load the font file into an ArrayBuffer ...

// either from an URL
const buffer = fetch('/fonts/my.woff').then(res => res.arrayBuffer());
// ... or from filesystem (node)
const buffer = require('fs').promises.readFile('./my.woff');
// ... or from an <input type=file id=myfile> (browser)
const buffer = document.getElementById('myfile').files[0].arrayBuffer();

... then we .parse() it into a Font instance

// if running in async context:
const font = opentype.parse(await buffer);
console.log(font);

// if not running in async context:
buffer.then(data => {
    const font = opentype.parse(data);
    console.log(font);
})
<details> <summary>Loading a WOFF2 font</summary>

WOFF2 Brotli compression perform 29% better than it WOFF predecessor. But this compression is also more complex, and would result in a much heavier (>10×!) opentype.js library (≈120KB => ≈1400KB).

To solve this: Decompress the font beforehand (for example with fontello/wawoff2).

// promise-based utility to load libraries using the good old <script> tag
const loadScript = (src) => new Promise((onload) => document.documentElement.append(
  Object.assign(document.createElement('script'), {src, onload})
));

const buffer = //...same as previous example...

// load wawoff2 if needed, and wait (!) for it to be ready
if (!window.Module) {
  const path = 'https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js'
  const init = new Promise((done) => window.Module = { onRuntimeInitialized: done});
  await loadScript(path).then(() => init);
}
// decompress before parsing
const font = opentype.parse(Module.decompress(await buffer));
</details>

Craft a font

It is also possible to craft a Font from scratch by defining each glyph bézier paths.

// this .notdef glyph is required.
const notdefGlyph = new opentype.Glyph({
    name: '.notdef',
    advanceWidth: 650,
    path: new opentype.Path()
});

const aPath = new opentype.Path();
aPath.moveTo(100, 0);
aPath.lineTo(100, 700);
// more drawing instructions...
const aGlyph = new opentype.Glyph({
    name: 'A',
    unicode: 65,
    advanceWidth: 650,
    path: aPath
});

const font = new opentype.Font({
    familyName: 'OpenTypeSans',
    styleName: 'Medium',
    unitsPerEm: 1000,
    ascender: 800,
    descender: -200,
    glyphs: [notdefGlyph, aGlyph]});

Saving a Font

Once you have a Font object (from crafting or from .parse()) you can save it back out as file.

// using node:fs
fs.writeFileSync("out.otf", Buffer.from(font.toArrayBuffer()));

// using the browser to createElement a <a> that will be clicked 
const href = window.URL.createObjectURL(new Blob([font.toArrayBuffer()]), {type: "font/opentype"});
Object.assign(document.createElement('a'), {download: "out.otf", href}).click();

The Font object

A Font represents a loaded OpenType font file. It contains a set of glyphs and methods to draw text on a drawing context, or to get a path representing the text.

Font.getPath(text, x, y, fontSize, options)

Create a Path that represents the given text.

Options is an optional {GlyphRenderOptions} object containing:

Note: there is also Font.getPaths() with the same arguments, which returns a list of Paths.

Font.draw(ctx, text, x, y, fontSize, options)

Create a Path that represents the given text.

Options is an optional object containing:

Font.drawPoints(ctx, text, x, y, fontSize, options)

Draw the points of all glyphs in the text. On-curve points will be drawn in blue, off-curve points will be drawn in red. The arguments are the same as Font.draw().

Font.drawMetrics(ctx, text, x, y, fontSize, options)

Draw lines indicating important font measurements for all glyphs in the text. Black lines indicate the origin of the coordinate system (point 0,0). Blue lines indicate the glyph bounding box. Green line indicates the advance width of the glyph.

Font.stringToGlyphs(string)

Convert the string to a list of glyph objects. Note that there is no strict 1-to-1 correspondence between the string and glyph list due to possible substitutions such as ligatures. The list of returned glyphs can be larger or smaller than the length of the given string.

Font.charToGlyph(char)

Convert the character to a Glyph object. Returns null if the glyph could not be found. Note that this function assumes that there is a one-to-one mapping between the given character and a glyph; for complex scripts, this might not be the case.

Font.getKerningValue(leftGlyph, rightGlyph)

Retrieve the value of the kerning pair between the left glyph (or its index) and the right glyph (or its index). If no kerning pair is found, return 0. The kerning value gets added to the advance width when calculating the spacing between glyphs.

Font.getAdvanceWidth(text, fontSize, options)

Returns the advance width of a text.

This is something different than Path.getBoundingBox(); for example a suffixed whitespace increases the advancewidth but not the bounding box or an overhanging letter like a calligraphic 'f' might have a quite larger bounding box than its advance width.

This corresponds to canvas2dContext.measureText(text).width

The Font.palettes object (PaletteManager)

This allows to manage the palettes and colors in the CPAL table, without having to modify the table manually.

Font.palettes.add(colors)

Add a new palette.

Font.palettes.delete(paletteIndex)

Deletes a palette by its zero-based index

Font.palettes.deleteColor(colorIndex, replacementIndex)

Deletes a specific color index in all palettes and updates all layers using that color with the color currently held in the replacement index

Font.palettes.cpal()

Returns the font's cpal table, or false if it does not exist. Used internally.

Font.palettes.ensureCPAL(colors)

Mainly used internally. Makes sure that the CPAL table exists or is populated with default values.

Font.palettes.extend(num)

Extend all existing palettes and the numPaletteEntries value by a number of color slots

Font.palettes.fillPalette(palette, colors, colorCount)

Fills a set of palette colors (from a palette index, or a provided array of CPAL color values) with a set of colors, falling back to the default color value, until a given count. It does not modify the existing palette, returning a new array instead! Use Font.palettes.setColor() instead if needed.

Font.palettes.getAll(colorFormat)

Returns an array of arrays of color values for each palette, optionally in a specified color format

Font.palettes.getColor(index, paletteIndex, colorFormat)

Get a specific palette by its zero-based index

Font.palettes.get(paletteIndex, colorFormat)

Get a specific palette by its zero-based index

Font.palettes.setColor(index, colors, paletteIndex)

Set one or more colors on a specific palette by its zero-based index

Font.palettes.toCPALcolor(color)

Converts a color value string to a CPAL integer color value

The Font.layers object (LayerManager)

This allows to manage the color glyph layers in the COLR table, without having to modify the table manually.

Font.layers.add(glyphIndex, layers, position)

Adds one or more layers to a glyph, at the end or at a specific position.

Font.layers.ensureCOLR()

Mainly used internally. Ensures that the COLR table exists and is populated with default values.

Font.layers.get(glyphIndex)

Gets the layers for a specific glyph

Font.layers.remove(glyphIndex, start, end = start)

Removes one or more layers from a glyph.

Font.layers.setPaletteIndex(glyphIndex, layerIndex, paletteIndex)

Sets a color glyph layer's paletteIndex property to a new index

Font.layers.updateColrTable(glyphIndex, layers)

Mainly used internally. Updates the colr table, adding a baseGlyphRecord if needed, ensuring that it's inserted at the correct position, updating numLayers, and adjusting firstLayerIndex values for all baseGlyphRecords according to any deletions or insertions.

The Font.variation object (VariationManager)

The VariationManager handles variable font properties using the OpenType font variation tables.

Font.variation.activateDefaultVariation()

Activates the default variation by setting its variation data as the font's default render options. Uses the default instance if available; otherwise, it defaults to the coordinates of all axes.

Font.variation.getDefaultCoordinates()

Returns the default coordinates for the font's variation axes.

Font.variation.getDefaultInstanceIndex()

Determines and returns the index of the default variation instance. Returns -1 if it cannot be determined.

Font.variation.getTransform(glyph, coords)

Just a shortcut for Font.variation.process.getTransform().

Font.variation.getInstanceIndex(coordinates)

Finds the index of the variation instance that matches the provided coordinates, or -1 if none match.

Font.variation.getInstance(index)

Retrieves a specific variation instance by its zero-based index.

Font.variation.set(instanceIdOrObject)

Sets the variation coordinates to be used by default for rendering in the font's default render options.

Font.variation.get()

Gets the current variation settings from the font's default render options.

The Font.variation.process object (VariationProcessor)

The VariationProcessor is a component of the VariationManager, used mainly internally for computing and applying variations to the glyphs in a variable font. It handles transformations and adjustments based on the font's variable axes and instances.

Font.variation.process.getNormalizedCoords(coords)

Returns normalized coordinates for the variation axes based on the current settings.

Font.variation.process.interpolatePoints(points, deltas, scalar)

Interpolates points based on provided deltas and a scalar value.

Font.variation.process.deltaInterpolate(original, deltaValues, scalar)

Calculates the interpolated value for a single point given original values, deltas, and a scalar.

Font.variation.process.deltaShift(points, deltas)

Applies delta values to shift points.

Font.variation.process.transformComponents(components, transformation)

Transforms components of a glyph using a specified transformation matrix.

Font.variation.process.getTransform(glyph, coords)

Retrieves a transformed copy of a glyph based on the provided variation coordinates, or the glyph itself if no variation was applied

Font.variation.process.getVariableAdjustment(adjustment)

Calculates the variable adjustment for a given adjustment parameter.

Font.variation.process.getDelta(deltas)

Selects the appropriate delta values from a collection of deltas based on the current variation settings.

Font.variation.process.getBlendVector()

Computes the blend vector for interpolations based on the current settings.

The Glyph object

A Glyph is an individual mark that often corresponds to a character. Some glyphs, such as ligatures, are a combination of many characters. Glyphs are the basic building blocks of a font.

Glyph.getPath(x, y, fontSize, options, font)

Get a scaled glyph Path object for use on a drawing context.

Glyph.getBoundingBox()

Calculate the minimum bounding box for the unscaled path of the given glyph. Returns an opentype.BoundingBox object that contains x1/y1/x2/y2. If the glyph has no points (e.g. a space character), all coordinates will be zero.

Glyph.draw(ctx, x, y, fontSize, options, font)

Draw the glyph on the given context.

Glyph.drawPoints(ctx, x, y, fontSize, options, font)

Draw the points of the glyph on the given context. On-curve points will be drawn in blue, off-curve points will be drawn in red. The arguments are the same as Glyph.draw().

Glyph.drawMetrics(ctx, x, y, fontSize)

Draw lines indicating important font measurements for all glyphs in the text. Black lines indicate the origin of the coordinate system (point 0,0). Blue lines indicate the glyph bounding box. Green line indicates the advance width of the glyph. The arguments are the same as Glyph.draw().

Glyph.toPathData(options), Glyph.toDOMElement(options), Glyph.toSVG(options), Glyph.fromSVG(pathData, options),

These are currently only wrapper functions for their counterparts on Path objects (see documentation there), but may be extended in the future to pass on Glyph data for automatic calculation.

Glyph.getLayers(font)

Gets the color glyph layers for this glyph from the specified font's COLR/CPAL tables

The Path object

Once you have a path through Font.getPath() or Glyph.getPath(), you can use it.

Path.draw(ctx)

Draw the path on the given 2D context. This uses the fill, stroke, and strokeWidth properties of the Path object.

Path.getBoundingBox()

Calculate the minimum bounding box for the given path. Returns an opentype.BoundingBox object that contains x1/y1/x2/y2. If the path is empty (e.g. a space character), all coordinates will be zero.

Path.toPathData(options)

Convert the Path to a string of path data instructions. See https://www.w3.org/TR/SVG/paths.html#PathData

Path.toSVG(options)

Convert the path to an SVG <path> element, as a string.

Path.fromSVG(pathData, options)

Retrieve path from SVG path data.

Either overwriting the path data for an existing path:

const path = new Path();
path.fromSVG('M0 0');

Or creating a new Path directly:

const path = Path.fromSVG('M0 0');

Path commands

Versioning

We use SemVer for versioning.

License

MIT

Thanks

We would like to acknowledge the work of others without which opentype.js wouldn't be possible: