opentype.js is JavaScript parser and writer for TrueType and OpenType fonts.

It allows you to access the alphabetic form of text from a browser or Node.js.

feature

  • Creates a Bezier path from a piece of text.
  • Composite glyphs (accented letters) are supported.
  • Support WOFF, OTF, TTF (all with TrueTypeglyfand PostScriptcffcontour)
  • Kerning is supported (using GPOS or kern tables).
  • Ligatures are supported.
  • Support for TrueType font hinting.
  • Support Arabic text rendering (see issue #364 and PR #359 #361)
  • Low memory mode can be selected (see #329)
  • Runs in the browser and Node.js.

Install

via CDN

Select one of the following sources for 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.module.js";
parse(...);
</script>

passnpmpackage manager

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

import opentype from 'opentype.js'

import { load } from 'opentype.js'

usage

Load WOFF/OTF/TTF fonts

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

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

Load WOFF2 font

WOFF2 Brotli compression performance better than WOFF predecessor29% better.But this compression is also more complex and will result in a heavier opentype.js library (~120KB => ~1400KB).

To fix this: uncompress the fonts beforehand (e.g. usingfontello/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));

Load fonts (1.x styles)

This example relies on the deprecated.load()method

// case 1: from an URL
const font = opentype.load('./fonts/my.woff', {}, {isUrl: true});
// case 2: from filesystem
const font = opentype.load('./fonts/my.woff', {}, {isUrl: false});

// ... play with `font` ...
console.log(font.supported);

write font

once you have aFontobject (by usingopentype.loador create a new object from scratch), you can write it back as a binary file.

In a browser, you can useFont.download()Instructs the browser to download the binary .OTF file. The name is based on the font name.

// Create the bézier paths for each of the glyphs.
// Note that the .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 glyphs = [notdefGlyph, aGlyph];
const font = new opentype.Font({
    familyName: 'OpenTypeSans',
    styleName: 'Medium',
    unitsPerEm: 1000,
    ascender: 800,
    descender: -200,
    glyphs: glyphs});
font.download();

If you want to check fonts usefont.toTables() Produces an object showing a data structure that maps directly to a binary value.if you want to get aArrayBuffer,usefont.toArrayBuffer().

font object

Font represents the loaded OpenType font file. It contains a set of glyphs and methods for drawing text in a drawing context, or for obtaining a path representing text.

  • glyphs: List of indices of glyph objects.
  • unitsPerEm: The X/Y coordinates in the font are stored as integers. This value determines the size of the grid. Common values ​​are 2048 and 4096.
  • ascender: Distance from the baseline of the highest ascender. Units are in fonts, not pixels.
  • descender: The distance from the lowest descent baseline. Units are in fonts, not pixels.

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

Create a path representing the given text.

  • x: The horizontal position of the beginning of the text. (default: 0)
  • y:textbaselinevertical position. (default: 0)
  • fontSize: Text size in pixels (default: 72).

options is an optional object containing:

  • kerning: if true consider kerning information (default: true)
  • features: an OpenType feature tagAn object as a key, and a boolean to enable each feature. Currently only the ligature features “liga” and “rlig” are supported (default: true).
  • hinting: if true use TrueType font hinting if available (default: false).

Note: there areFont.getPathsThe same argument returns a list of paths.

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

Create a path representing the given text.

  • ctx: 2D drawing context, such as Canvas.
  • x: The horizontal position of the beginning of the text. (default: 0)
  • y:textbaselinevertical position. (default: 0)
  • fontSize: Text size in pixels (default: 72).

options is an optional object containing:

  • kerning: if true consider kerning information (default: true)
  • features: an OpenType feature tagAn object as a key, and a boolean to enable each feature. Currently only the ligature features “liga” and “rlig” are supported (default: true).
  • hinting: if true use TrueType font hinting if available (default: false).

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

Draw the points of all glyphs in the text. Points on the curve will be drawn in blue, and points outside the curve will be drawn in red.parameters withFont.draw.

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

Draw lines to indicate significant font sizes for all glyphs in the text. The black line represents the origin of the coordinate system (point 0,0). Blue lines represent glyph bounding boxes. The green line indicates the advance width of the glyph.

Font.stringToGlyphs(string)

Convert a string to a list of glyph objects. Note that there is no strict one-to-one correspondence between strings and glyph lists due to possible substitutions (eg ligatures). The returned list of glyphs can be larger or smaller than the length of the given string.

Font.charToGlyph(char)

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

Font.getKerningValue(leftGlyph, rightGlyph)

Retrieves between the left glyph (or its index) and the right glyph (or its index)Kerningright value. Returns 0 if no kerning pair is found. The kerning value is added to the lead width when calculating the spacing between glyphs.

Font.getAdvanceWidth(text, fontSize, options)

Returns the advance width of the text.

This differs from Path.getBoundingBox() in that for example a trailing space increases the advancewidth but not the bounding box, or a dangling letter like a calligraphic ‘f’ may have a much larger bounding box than its advancewidth.

This corresponds to canvas2dContext.measureText(text).width

  • fontSize: Text size in pixels (default: 72).
  • options: See Font.getPath

glyph object

A glyph is a single token, usually corresponding to a character. Some glyphs, such as ligatures, are combinations of many characters. Glyphs are the basic building blocks of fonts.

  • font: a reference to the objectFont.
  • name: glyph name (e.g. “Aring”, “five”)
  • unicode: the primary unicode value of this glyph (can beundefined).
  • unicodes: List of unicode values ​​for this glyph (1 in most cases, can be empty).
  • index: The index number of the glyph.
  • advanceWidth: The width the pen advances when drawing this glyph.
  • leftSideBearing: the horizontal distance from the previous character to the origin (0, 0); a negative value indicates a dangling
  • xMin, yMin, xMax, yMax: The bounding box of the glyph.
  • path: The original, unscaled path of the glyph.

Glyph.getPath(x, y, fontSize)

Gets a scaled glyph Path object that we can draw in the drawing context.

  • x: The horizontal position of the glyph. (default: 0)
  • y: glyph baselineofvertical position. (default: 0)
  • fontSize: font size in pixels (default: 72).

Glyph.getBoundingBox()

Computes the minimum bounding box for the unscaled path of a given glyph.returnopentype.BoundingBoxAn object containing x1/y1/x2/y2. If the glyph has no dots (such as a space character), all coordinates will be zero.

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

Draws the glyph in the given context.

  • ctx: The drawing context.
  • x: The horizontal position of the glyph. (default: 0)
  • y: glyph baselineofvertical position. (default: 0)
  • fontSize: font size, in pixels (default: 72).

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

The points at which the glyph is drawn in the given context. Points on the curve will be drawn in blue, and points outside the curve will be drawn in red.parameters withGlyph.draw.

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

Draw lines to indicate significant font sizes for all glyphs in the text. The black line represents the origin of the coordinate system (point 0,0). Blue lines represent glyph bounding boxes. The green line indicates the advance width of the glyph.parameters withGlyph.draw.

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

These are currently just wrapper functions for the corresponding objects on the Path object (see the docs there), but may be extended in the future to pass Glyph data for automatic calculations.

path object

Once there is a passFont.getPathor the path ofGlyph.getPathyou can use it.

  • commands: path command. Each command is a dictionary containing type and coordinates. See below for an example.
  • fill: the fill color ofPath.Color is a CSS colorstring. (default: ‘black’)
  • stroke: the stroke color ofPath.Color is a CSS colorstring. (default::nullpaths will not be stroked)
  • strokeWidth: the line thickness ofPath. (Default: 1, but due tostrokenull, so the stroke will not be drawn)

Path.draw(ctx)

Draws a path in the given 2D context.This uses the object’sfill,strokeandstrokeWidthAttributesPath.

Path.getBoundingBox()

Computes the minimum bounding box for a given path.returnopentype.BoundingBoxAn object containing x1/y1/x2/y2. If the path is empty (such as a space character), all coordinates will be zero.

Path.toPathData(options)

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

  • options:
    • decimalPlaces: The number of decimal places for floating point values. (default: 2)
    • optimize: apply some optimizations to path data, such as removing unnecessary/duplicate commands (true/false, default: true)
    • flipY: Whether to flip the Y axis of the path data, since SVG and font paths use an inverted Y axis. (true: calculate from bounding box, false: disabled; default: true)
    • flipYBase: The base value for the base rollover calculation. You probably want to calculate it based on the font’s ascending and descending values. (default: automatically computed from bounding box of path data)

Path.toSVG(options)

Convert a path to an SVG element, as a string.

  • options: see Path.toPathData

Path.fromSVG(pathData, options)

Retrieve a path from the SVG path data.Path data overwriting an existing path

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

or create a new path directly:

const path = Path.fromSVG('M0 0');
  • pathData: a string of SVG path commands, or (in browser context only) aSVGPathElement
  • options:
    • decimalPlaces, optimize, flipY, flipYBase: see Path.toPathData
    • scale: scaling value to apply to all command coordinates (default: 1)
    • x/ y: Offset to apply to all command coordinates on the x or y axis (default: 0)

path command

  • move to: Move to a new location. This creates a new outline. example:{type: 'M', x: 100, y: 200}
  • Line To: Draw a line from the previous position to the given coordinates. example:{type: 'L', x: 100, y: 200}
  • Curve To : Draw a Bezier curve from the current position to the given coordinates. example:{type: 'C', x1: 0, y1: 50, x2: 100, y2: 200, x: 100, y: 200}
  • Quad To: Draws a quadratic Bezier curve from the current position to the given coordinates. example:{type: 'Q', x1: 0, y1: 50, x: 100, y: 200}
  • closure: Close path. If stroked, this will draw a line from the first point to the last point of the outline. example:{type: 'Z'}

#opentype.js #Homepage #Documentation #Downloads #JavaScript #Read #Write #OpenType #Fonts #News Fast Delivery

Leave a Comment

Your email address will not be published. Required fields are marked *