MCPcopy
hub / github.com/opentypejs/opentype.js

github.com/opentypejs/opentype.js @2.0.0 sqlite

repository ↗ · DeepWiki ↗ · release 2.0.0 ↗
591 symbols 1,296 edges 119 files 145 documented · 25%
README

opentype.js

Latest version on npm npm downloads, yearly MIT License GitHub Workflow Status (with event)

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

  • Create a bézier path out of a piece of text.
  • Support for composite glyphs (accented letters).
  • Support for WOFF, OTF, TTF (both with TrueType glyf and PostScript cff outlines)
  • Support for kerning (Using GPOS or the kern table).
  • Support for ligatures.
  • Support for TrueType font hinting.
  • Support arabic text rendering (See issue #364 & PR #359 #361)
  • Support for emojis and other SVG or COLR/CPAL color glyphs
  • A low memory mode is available as an option (see #329)
  • Runs in the browser and Node.js.

Installation

via CDN

Select one of the following sources in the next example:

  • https://opentype.js.org/dist/opentype.js
  • https://cdn.jsdelivr.net/npm/opentype.js
  • https://unpkg.com/opentype.js

<script src="https://your.favorite.cdn/opentype.js"></script>
<script>opentype.parse(...)</script>


<script type=module>
import { parse } from "https://unpkg.com/opentype.js/dist/opentype.module.js";
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:

  • Fork the opentype.js repo
  • clone your fork git clone git://github.com/yourname/opentype.js.git
  • move into the project cd opentype.js
  • install needed dependencies with npm install
  • make your changes
    • option A: for a simple build, use npm run build
    • option B: for a development server, use npm run start and navigate to the /docs folder
  • check if all still works fine with npm run test
  • commit and open a Pull Request with your changes. Thank you!

Maintainer Releases

Releases are published from the manual Publish package to npm workflow.

  1. Confirm the target version, for example 1.3.5, and make sure master is green.
  2. Run the workflow from master with dryRun: true and npmDistTag: latest.
  3. Inspect the dry-run output, especially the package version and packed files.
  4. Re-run the workflow with the same version and dryRun: false.

The release workflow runs preflight checks, publishes to npm, then creates the matching git tag and GitHub release.

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);
})

Loading a WOFF2 font

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));

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.

  • glyphs: an indexed list of Glyph objects.
  • unitsPerEm: X/Y coordinates in fonts are stored as integers. This value determines the size of the grid. Common values are 2048 and 4096.
  • ascender: Distance from baseline of highest ascender. In font units, not pixels.
  • descender: Distance from baseline of lowest descender. In font units, not pixels.

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

Create a Path that represents the given text. * x: Horizontal position of the beginning of the text. (default: 0) * y: Vertical position of the baseline of the text. (default: 0) * fontSize: Size of the text in pixels (default: 72). * options: {GlyphRenderOptions} passed to each glyph, see below

Options is an optional {GlyphRenderOptions} object containing: * script: script used to determine which features to apply (default: "DFLT" or "latn") * language: language system used to determine which features to apply (default: "dflt") * kerning: if true takes kerning information into account (default: true) * features: an object with OpenType feature tags as keys, and a boolean value to enable each feature. Currently only ligature features "liga" and "rlig" are supported (default: true). * hinting: if true uses TrueType font hinting if available (default: false). * colorFormat: the format colors are converted to for rendering (default: "hexa"). Can be "rgb"/"rgba" for rgb()/rgba() output, "hex"/"hexa" for 6/8 digit hex colors, or "hsl"/"hsla" for hsl()/hsla() output. "bgra" outputs an object with r, g, b, a keys (r/g/b from 0-255, a from 0-1). "raw" outputs an integer as used in the CPAL table. * fill: font color, the color used to render each glyph (default: "black")

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. * ctx: A 2D drawing context, like Canvas. * x: Horizontal position of the beginning of the text. (default: 0) * y: Vertical position of the baseline of the text. (default: 0) * fontSize: Size of the text in pixels (default: 72). * options: {GlyphRenderOptions} passed to each glyph, see Font.getPath()

Options is an optional object containing: * kerning: if true, takes kerning information into account (default: true) * features: an object with OpenType feature tags as keys, and a boolean value to enable each feature. Currently only ligature features "liga" and "rlig" are supported (default: true). * hinting: if true uses TrueType font hinting if available (default: false).

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 * fontSize: Size of the text in pixels (default: 72). * options: {GlyphRenderOptions}, see Font.getPath()

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. * colors: (optional) colors to add to the palette, differences to existing palettes will be filled with the defaultValue.

Font.palettes.delete(paletteIndex)

Deletes a palette by its zero-based index * paletteIndex: zero-based palette 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 * colorIndex: index of the color that should be deleted * replacementIndex: index (according to the palette before deletion) of the color to replace in layers using the color to be to deleted

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. * colors: (optional) colors to populate on creation returns true if it was created, false if it already existed.

Font.palettes.extend(num)

Extend all existing palettes and the numPaletteEntries value by a number of color slots * num: number of additional color slots to add to all palettes

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. * palette: palette index or an Array of CPAL color values to fill the palette with, the rest will be filled with the default color * colors: array of color values to fill the palette with, in a format supported as an output of colorFormat in {GlyphRenderOptions}, see Font.getPath(). CSS color names are also supported in browser context. * colorCount: Number of colors to fill the palette with, defaults to the value of the numPaletteEntries field

Font.palettes.getAll(colorFormat)

Returns an array of arrays of color values for each palette, optionally in a specified color format * colorFormat: (optional) See {GlyphRenderOptions} at Font.getPath(), (default: "hexa")

Core symbols most depended-on inside this repo

get
called by 111
src/layers.mjs
hex
called by 109
test/testutil.mjs
u16
called by 101
test/font-generation-helpers.mjs
unhex
called by 65
test/testutil.mjs
i16
called by 60
test/font-generation-helpers.mjs
parseColor
called by 39
src/tables/cpal.mjs
uncompressTable
called by 31
src/opentype.mjs
add
called by 26
src/layers.mjs

Shape

Function 525
Method 56
Class 10

Languages

TypeScript100%

Modules by API surface

src/hintingtt.mjs113 symbols
src/tables/cff.mjs40 symbols
src/variationprocessor.mjs20 symbols
test/font-generation-helpers.mjs17 symbols
src/palettes.mjs16 symbols
src/variation.mjs15 symbols
src/parse.mjs14 symbols
test/tokenizer.spec.mjs13 symbols
src/tiny-inflate@1.0.3.esm.mjs12 symbols
src/svgimages.mjs12 symbols
src/features/featureQuery.mjs12 symbols
src/bidi.mjs11 symbols

Dependencies from manifests, versioned

@types/opentype.js0.7.2 · 1×
esbuild0.23.1 · 1×
eslint9.10.0 · 1×
mocha10.7.3 · 1×

For agents

$ claude mcp add opentype.js \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact