Code Monkey home page Code Monkey logo

opentype.js's Introduction

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:

<!-- 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>

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!

Usage

Loading a WOFF/OTF/TTF font

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

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/[email protected]/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));

Loading a font (1.x style)

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

Writing a font

Once you have a Font object (either by using opentype.load() or by creating a new one from scratch) you can write it back out as a binary file.

In the browser, you can use Font.download() to instruct the browser to download a 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 inspect the font, use font.toTables() to generate an object showing the data structures that map directly to binary values. If you want to get an ArrayBuffer, use font.toArrayBuffer().

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")
Font.palettes.getColor(index, paletteIndex, colorFormat)

Get a specific palette by its zero-based index

  • index: zero-based index of the color in the palette
  • paletteIndex: zero-based palette index (default: 0)
  • colorFormat: (optional) See {GlyphRenderOptions} at Font.getPath(), (default: "hexa")
Font.palettes.get(paletteIndex, colorFormat)

Get a specific palette by its zero-based index

  • paletteIndex: zero-based palette index
  • colorFormat: (optional) See {GlyphRenderOptions} at Font.getPath(), (default: "hexa")
Font.palettes.setColor(index, colors, paletteIndex)

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

  • index: zero-based color index to start filling from
  • color: color value or array of color values in a color notation supported as an output of colorFormat in {GlyphRenderOptions}, see Font.getPath(). CSS color names are also supported in browser context.
  • paletteIndex: zero-based palette index (default: 0)
Font.palettes.toCPALcolor(color)

Converts a color value string to a CPAL integer color value

  • color: string in a color notation supported as an output of colorFormat in {GlyphRenderOptions}, see Font.getPath(). CSS color names are also supported in browser context.
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.

  • glyphIndex: glyph index to add the layer(s) to.
  • layers: layer object {glyph, paletteIndex}/{glyphID, paletteIndex} or array of layer objects.
  • position: position to insert the layers at (will default to adding at the end).
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

  • glyphIndex Returns an array of {glyph, paletteIndex} layer objects.
Font.layers.remove(glyphIndex, start, end = start)

Removes one or more layers from a glyph.

  • glyphIndex: glyph index to remove the layer(s) from
  • start: index to remove the layer at
  • end: (optional) if provided, removes all layers from start index to (and including) end index
Font.layers.setPaletteIndex(glyphIndex, layerIndex, paletteIndex)

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

  • glyphIndex: glyph in the font by zero-based glyph index
  • layerIndex: layer in the glyph by zero-based layer index
  • paletteIndex: new color to set for the layer by zero-based index in any palette
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.

  • Returns: An object mapping axis tags to their default values.
Font.variation.getDefaultInstanceIndex()

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

  • Returns: Integer representing the default instance index or -1.
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.

  • coordinates: Object with axis tags as keys and variation values as corresponding values.
  • Returns: Integer of the matching instance index or -1.
Font.variation.getInstance(index)

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

  • index: Zero-based index of the variation instance.
  • Returns: Object representing the variation instance, or null if the index is invalid.
Font.variation.set(instanceIdOrObject)

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

  • instanceIdOrObject: Either the zero-based index of a variation instance or an object mapping axis tags to variation values.
Font.variation.get()

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

  • Returns: Object with the current variation settings.
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.

  • coords: The coordinates object to normalize (or the variation coords in the font's defaultRenderOptions by default)
  • Returns: Normalized coordinates as an object mapping axis tags to normalized values.
Font.variation.process.interpolatePoints(points, deltas, scalar)

Interpolates points based on provided deltas and a scalar value.

  • points: Array of original points.
  • deltas: Array of point deltas.
  • scalar: Scalar value for interpolation.
  • Returns: Array of interpolated points.
Font.variation.process.deltaInterpolate(original, deltaValues, scalar)

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

  • original: Original value of the point.
  • deltaValues: Array of delta values for the point.
  • scalar: Scalar value for interpolation.
  • Returns: Interpolated value.
Font.variation.process.deltaShift(points, deltas)

Applies delta values to shift points.

  • points: Array of original points.
  • deltas: Array of deltas to apply.
  • Returns: Array of shifted points.
Font.variation.process.transformComponents(components, transformation)

Transforms components of a glyph using a specified transformation matrix.

  • components: Components of the glyph.
  • transformation: Transformation matrix to apply.
  • Returns: Transformed components.
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

  • glyph: Glyph or index of glyph to transform.
  • coords: Variation coords object (or the variation coords in the font's defaultRenderOptions by default)
  • Returns: opentype.Glyph
Font.variation.process.getVariableAdjustment(adjustment)

Calculates the variable adjustment for a given adjustment parameter.

  • adjustment: Adjustment parameter.
  • Returns: Adjusted value based on current variation settings.
Font.variation.process.getDelta(deltas)

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

  • deltas: Collection of delta values.
  • Returns: Appropriate delta values for the current settings.
Font.variation.process.getBlendVector()

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

  • Returns: Blend vector used for interpolation calculations.

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.

  • font: A reference to the Font object.
  • name: The glyph name (e.g. "Aring", "five")
  • unicode: The primary unicode value of this glyph (can be undefined).
  • unicodes: The list of unicode values for this glyph (most of the time this will be 1, can also be empty).
  • index: The index number of the glyph.
  • advanceWidth: The width to advance the pen when drawing this glyph.
  • leftSideBearing: The horizontal distance from the previous character to the origin (0, 0); a negative value indicates an overhang
  • xMin, yMin, xMax, yMax: The bounding box of the glyph.
  • path: The raw, unscaled path of the glyph.
Glyph.getPath(x, y, fontSize, options, font)

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

  • x: Horizontal position of the glyph. (default: 0)
  • y: Vertical position of the baseline of the glyph. (default: 0)
  • fontSize: Font size in pixels (default: 72).
  • options: {GlyphRenderOptions}, see Font.getPath()
  • font: a font object, needed for rendering COLR/CPAL fonts to get the layers and colors
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.

  • ctx: The drawing context.
  • x: Horizontal position of the glyph. (default: 0)
  • y: Vertical position of the baseline of the glyph. (default: 0)
  • fontSize: Font size, in pixels (default: 72).
  • options: {GlyphRenderOptions}, see Font.getPath()
  • font: a font object, needed for rendering COLR/CPAL fonts to get the layers and colors
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.

  • commands: The path commands. Each command is a dictionary containing a type and coordinates. See below for examples.
  • fill: The fill color of the Path. Color is a string representing a CSS color. (default: 'black')
  • stroke: The stroke color of the Path. Color is a string representing a CSS color. (default: null; the path will not be stroked)
  • strokeWidth: The line thickness of the Path. (default: 1, but if stroke is null no stroke will be drawn)
Path.draw(ctx)

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

  • ctx: The drawing context.
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

  • options:
    • decimalPlaces: The amount of decimal places for floating-point values. (default: 2)
    • optimize: apply some optimizations to the path data, e.g. removing unnecessary/duplicate commands (true/false, default: true)
    • flipY: whether to flip the Y axis of the path data, because SVG and font paths use inverted Y axes. (true: calculate from bounding box, false: disable; default: true)
    • flipYBase: Base value for the base flipping calculation. You'll probably want to calculate this from the font's ascender and descender values. (default: automatically calculate from the path data's bounding box)
Path.toSVG(options)

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

  • options: see Path.toPathData()
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');
  • pathData: Either a string of SVG path commands, or (only in browser context) an SVGPathElement
  • options:
    • decimalPlaces, optimize, flipY, flipYBase: see Path.toPathData()
    • scale: scaling value applied to all command coordinates (default: 1)
    • x/y: offset applied to all command coordinates on the x or y axis (default: 0)

Path commands

  • Move To: Move to a new position. This creates a new contour. Example: {type: 'M', x: 100, y: 200}
  • Line To: Draw a line from the previous position to the given coordinate. Example: {type: 'L', x: 100, y: 200}
  • Curve To: Draw a bézier curve from the current position to the given coordinate. Example: {type: 'C', x1: 0, y1: 50, x2: 100, y2: 200, x: 100, y: 200}
  • Quad To: Draw a quadratic bézier curve from the current position to the given coordinate. Example: {type: 'Q', x1: 0, y1: 50, x: 100, y: 200}
  • Close: Close the path. If stroked, this will draw a line from the first to the last point of the contour. Example: {type: 'Z'}

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:

opentype.js's People

Contributors

adri326 avatar axkibe avatar brawer avatar bulyshko avatar connum avatar dependabot[bot] avatar fdb avatar fpirsch avatar harbs avatar ilovepie avatar jolg42 avatar joshmarinacci avatar lachmanski avatar louisremi avatar martinbolot avatar mathieuruellanmyscript avatar mattlag avatar miguelsousa avatar mottie avatar moyogo avatar ollimeier avatar pomax avatar puria avatar rafallyczkowskiadylic avatar solomancode avatar sunng87 avatar taylorb-monotype avatar tshinnic avatar vildan avatar yne avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

opentype.js's Issues

Any way to support this project?

I've been following this project for a while now and I'm very interested in using it in a project of mine to dynamically generate textures to be used in WebGL, which would then be used for text animations. Naturally, I would want this parser to be as well-developed and robust as possible.

Sadly, I don't have the coding skills to contribute to this project. Is there any other way I can help contribute to this project (donations etc...)?

Also, is there a good resource or book where I can learn about font parsing so I can actually develop the skills to be useful to this project?

Thanks.

getCFFString bug

In 'cff.js', line 153, this should be "index < 391", because the length of the cffStandardStrings collection is only 391.

function getCFFString(strings, index) {
    if (index <= 391) {
        index = encoding.cffStandardStrings[index];
    } else {
        index = strings[index - 391];
    }
    return index;
}

Without the change, I believe this just returns null for index 391.

Possible bugs detected while porting code to C#

Having ported all the code to C# I also had to go through it all, so free code audit! :D I found some small things which were pretty obviously wrong, and here they are.

In 'font.js', line 66:

if (this.glyphNames.glyphIndexToName) {
    return '';
}
return this.glyphNames.glyphIndexToName(gid);

Should probably be "if (!this.glyphNames.glyphIndexToName) {".

In 'gpos.js', line 167 and 171:

    // Get the kerning value for a specific glyph pair.
    return function(leftGlyph, rightGlyph) {
        if (!covered[leftGlyph]) return 0;
        var class1 = getClass1(leftGlyph),
            class2 = getClass2(rightGlyph),
            kerningRow = kerningMatrix[class1];
        return kerningRow ? kerningRow[class2] : 0;
    };

Instead of returning 0 here, it should probably return null instead to be compatible with the format 1 lookup function above it which does not return a value if no kerning value is found, which would return null. Returning 0 here might create incorrect kerning values, as there's no way to distinguish between "unknown" and "the kerning should be zero".

In 'maxp.js', line 15:

if (maxp.majorVersion === 1) {

maxp was just declared and no member variable called majorVersion is set, so this code would never run. Should this perhaps be something more like this? if (Math.floor(maxp.version) === 1)

In 'post.js', line 45:

    post.offset = new Array(post.numberOfGlyphs);
    for (i = 0; i < post.numberOfGlyphs; i++) {
        post.offset = p.parseChar();
    }
    break;

This seems like you'd really want to add the array subscript, so: post.offset[i] = p.parseChar();

Add code quality tools

As the project grows it is important that the quality of the code remains high: no regressions should be introduced and the overal coding style remains consistent.

For tests, set up a testing suite that runs automatically and catches regressions with built-in fonts.

For code consistency, set up JSHint. This should be integrated in a npm test task, and be checked in continuous integration (so it can automatically test pull requests).

In addition, also mention these guidelines in a CONTRIBUTING.md file.

Waiting font loaded

Hi,

Thanks for the previous reply. Now I have a question about loading font without callback function. I need it because I call the function below from flex. Flex can't send callback function.

// This function is something I need
function getPath(text) {
// no callback function. just wait
opentype.load('fonts/ariblk.ttf');
var path = font.getPath(text, 0, 150, 72);
var json = JSON.stringify(path);
return json;
}

Can I load font file without callback to make the process wait?

Problems with some of Cyrillic letters in Arial font.

When Arial.ttf from ttf-mscorefonts-installer debian package is used opentype draws incorrectly some of Cyrillic letters. For example Cyrillic 'Э' is drawn as Euro symbol. As well as 'Я' is drawn as 'R'. It seems that those glyphs are using some kind of 'mirror' transform which is not supported by opentype.

opentypebug

Glyph copy constructor

It would be very useful if there was a Glyph copy constructor, or factory method, so that modifications to a glyph can be made to copies, rather than the original (thus allowing things like modifying the same letter in a string with multiple instances in different ways).

The new Glyph constructor looks pretty good, but it might be useful to add an if(options.points) { /* this is a copy constructor call */ } so that copies are easily constructed

List of unicode characters in font?

I'm looking how I could retrieve a list of unicode characters available within a font. This is useful in scenarios where you need to build an index of characters in a font to be used elsewhere. For example to store a unicode character and it's associated glyph details to be persisted in a database and used in another system.

I can see a set of glyph names and glyphs themselves, but no way to get a list of actual characters or unicode values in the font.

Is this possible today and I simply missed how to do it?

Thanks!

Add support for PostScript fonts

OpenType font files can contain both TrueType or PostScript outlines. Currently we only support TrueType outlines. We should support both.

Incompatibility with Safari 6?

In Safari 6.1.4, constructor.name is undefined. This results in Parser's isDataView property always returning false. I'm not sure if there is a good fix, but a hackish adjustment could be made.

It's ugly, but the following resolves the issue:

this.isDataView = (data.constructor.name === 'DataView') || (data.constructor.toString().match(/DataView/) !== null)

how to get point-along-a-path from path object

I am drawing a glyph shape and getting its path using font.getPath(). This method gives me a path object containing an array of draw commands. Now, I want to be able to find any arbitrary point on the path curve for a given x and y value coordinates (similar to SVG function getPointAtLength().

How to do this?

separating the two part of "getting font data" and "drawing it" to different libraries

one will only extract raw data that can also be used for the second library for drawing.
it has the benefit that it will make this lib more lighter and more flexible for building libraries that use this lib. (for example the discussion about using angular with the font data).
and i think it would be more useful in future for making opentype.js a lib that also write fonts

Bower support

It would be great if OpenType could be installed using the Bower package manager.

Suport for WOFF File Format

Are there any plans to support Web-Fonts (WOFF) i.e. to read from Google-Fonts and the such? As far as I understood, on could actually use zlib.js to decompress the woff format?

Doesn't work on IE11

I took a look at the demo in IE11 and the font playground is all garbled up. Here's a screenshot.

untitled

This is not a problem on Chrome.

Lazy parsing

Currently, opentype.js loads the entire font at startup. However, on large fonts like Arial Unicode MS, this takes a significant amount of time. Instead, opentype.js should lazily parse the requested glyph (outlines) whenever they're requested first, instead of on startup.

Issue with Glyph Mapping

Using the free "Open Sans Regular Italic" TrueType font and requesting a glyph for the character "I" yields in a returned glyph code of zero which is surely wrong and returns the typical "no-char" rectangle. Using the glyph inspector of opentype.js however shows a number of "44" for the letter "I".
Having debugged seems that CmapEncoding.prototype.charToGlyphIndex returns zero but I couldn't figure why not having really understood what the code does.

The font file mentioned can be gathered from here: http://www.fontsquirrel.com/fonts/open-sans (Choose "Italic" in the style box, then download TTF)

Syntax error in latest bower.json

Hi,

Just wanted to install from latest commit as there're some issues with the tagged 0.2.0 version, however getting a syntax error from bower:

bower opentype.js#3e9f760b421cf66426ee94b6177197e403698335 EMALFORMED Failed to read /var/folders/p5/58_0mhcx0sbd24yn_8297vf40000gn/T/aadam/bower/opentype.js-37523-NkFoX4/bower.json

Additional error details:
Unexpected token ]

Looking at the current bower.json I can see that there's an ending comma ',' before the closing square bracket and I guess that might cause the issue

Release v0.3.1

Current master has been updated from v0.3.0 and many problems are fixed.

Would you mind publishing a new version to npm and bower?

Handling unicode ranges and glyph lookup

Opentype puts a whole new spin on working with a new music notation OTF called Bravura. The Bravura font is an open standard and large as it covers most music symbols known to mankind. It is defined in the unicode user space as multiple sections grouping the many types/classes of music symbols into unicode ranges. Browse the ranges and diverse music glyphs here : http://www.smufl.org/version/latest

Not all music publishing will require all the sections defined by Bravura. What would be helpful in Opentype is to be able to be able to parse only given unicode ranges or a specific list into a Opentype Font. Maybe this list format can be defined as JSON to act as a parse filter?

It would also be good to see what unicode code point a parsed glyph has and then to be able to lookup a given parsed glyph or range of glyphs by their unicode values.

Support for GPOS table parsing

Most fonts from Google repo (http://www.google.com/fonts) use the GPOS table for kerning data, and many don't include the old "kern" section, which currently causes missing kerning data from opentype.js.

IMO this is an important feature to support. Safari and Firefox both turn on kerning by default for all text. Not being able to take kerning into account leads to:

  • Inconsistent drawing results between native text and custom ones on the canvas elements.
  • Inability to accurately measure the size of a piece of text with kerning = true, which prevents usage of opentype.js for layout calculation that relies on text measurement.

Is it possible to get the middle skeleton path of glyphs

The font.getPath() method is giving me a path consisting of inner and outer boundaries of glyphs. I want to be able to find a skeletal path that goes through the middle of the glyph path. See the red line in the below attached image.
skeleton

Currently, I am following a circuitous approach:

  • going through each glyph's path,
  • finding out the indexes of relevant points on the outer border
  • compute the middle points on them and connect them with a line.

For example, from the above fig., to draw a vertical line skeleton for the left leg of "M", I take the middle of points (1,11) and (12,13) and then draw a line through the computed middle points.

This approach is tedious and not scalable. This is also inaccurate, if I use a different font (because the point numbers are different).

Is there a generic way, in which I can draw a middle line skeleton, that can draw straight line based glyphs as well as curved ones?

I considered using ctx.scale() and ctx.translate() to scale down the outer border path to create what looks like a middle skeleton. But, this seems to be not so accurate in case of curved paths, and especially if the font size changes.

Any clues how to approach this?

glyph lsb and rsb

It would be incredibly useful if the Glyph object also came with an lsb and rsb value, so that font-indicated glyph based alignment becomes possible.

Modularize the code base

Currently opentype.js is over 2,000 lines of JS. To make hacking on the code more manageable it might be a good idea to split it up into modules.

Some rough suggestions:

  • Paths
  • Primitive parsing functions (getByte, ...)
  • Font and Glyph object
  • CFF encoding tables
  • OpenType table parsers
  • CFF table parsers
  • Main entry points

There is an abundance of choice around build tools and I'd love to keep things simple. My current suggestion is to use Browserify and a simple package.json file (See this article for more info).

opentype.load fails when module is included by Browserify

Since Browserify provides module.exports capability to modules loaded in a browser, it winds up tricking opentype.js into trying to do an fs.readFile in the browser.

Would it be sensible to expose loadFromUrl and loadFromFile so that they can be called explicitly in a case like this?

Bug in charToGlyph

Hi, thanks for opentype.js, it's very useful. Though, I found a bug in charToGlyph:

I have the umlauts äöüß in my text. This works flawless in FreeType with both fonts I use but it only works with one font of the two fonts in opentype.js. The problematic font is Cousine.ttf.

The ASCII code of ö is 246. According to FreeType it's glyph 181 in Cousine but opentype.js returns glyph 168. So instead of getting my ö I get an é. The same happens with the other umlauts (and only with them).

Could you please check on that?

Thanks!

Make Font object structure more similar to OTF file

I see you are creating about 20 properties on File object (ascender, copyright, descender, description, designer ...). All these properties are already stored in Font.tables.

I think it is convenient for user to get these data right from tables, he can learn something about font file structure at the same time. I don't see any reason for such redundancy, it also makes file object "messy".

Unicode characters exception. (TypeError: Cannot read property '0' of undefined)

In the library's version uploaded to the project's website (gh-pages branch) at:
http://nodebox.github.io/opentype.js/index.html

Using the font DroidSansFallbackFull.ttf (https://github.com/android/platform_frameworks_base/blob/master/data/fonts/DroidSansFallbackFull.ttf)

Chinese characters, I use "零" for testing, display properly:
screen shot 2014-10-18 at 6 45 19 pm

Using the latest opentype (master branch) an exception is thrown:
TypeError: Cannot read property '0' of undefined
screen shot 2014-10-18 at 6 45 44 pm

As an extra note: During my testing, the version in the gh-pages branch seems to perform a lot faster than the version in the master branch.

Incorrect glyph paths

I am evaluating switching from a proprietary system I wrote to render glyphs to using opentype.js. I was comparing output for Helvetica and notice that when using opentype.js there are flat spots on the tops of some of the glyphs, such as "e" and "c". Shown here:

opentype-render

If you compare this to my code, which is drawing the same glyphs to a canvas, however I get the path data from converting the ttf to svg (using font forge) then using the svg path data to execute canvas drawing commands:

custom-render

You can see the difference. Now, I double checked this again with iWork Pages, using the Helvetica font that ships with OSX and the source font for my custom rendering:

iwork-pages-render

...and there are no flat spots; the output matches my output.

Can you please lend some insight on what you believe is happening here? It seems that incorrect params are being passed to bezierCurveTo or quadraticCurveTo; or they aren't completing the path properly.

Thanks!

Loading system fonts?

Hi,

I am just wondering if I can load system fonts which already exist in windows/fonts. Downloading each single font files gets whole process slow even though user's computer already has system fonts.

opentype.load('fonts/ariblk.ttf', function (err, font) {
});

Thanks,

incorrect placement of component

When loading Roboto-Black, glyph 109 '«' U+00AB has its first component in the wrong position:
dx: 245
dy: 221
but it should be:
dx :-11
dy:-35

don't output 'Z' commands for whitespace

Hi, I think you output a 'Z' command for every glyph, including blanks, which is a bit strange since you have issued no 'M' or any drawing command before.

I found it with SVG where it's illegal, it's really visible when you start the chunk of text with a space, the first command is a Z.

Better API for glyphs.

It's currently quite hard to get access to glyph paths and boundaries.

Work out the API for glyphs to support getting the path, and supporting drawing.

How to get ascent and descent

I'm implementing a Canvas compatible API and I would like to get the ascent and descent of a font. I can calculate the min and max y values for a particular run of text, but then it will be dependent on that particular text. For example, 'GG' would return different results than 'Gg'. Is there a way to get the heights for the entire font instead of just particular glyphs?

How do I use opentype.js with NodeJS?

I created a simple test using the readme example code and I am unable to load the module.

this code:

var opentype = require('opentype');
var fs = require('fs');
var path = require('path');
opentype.load('SourceSansPro-Italic.ttf', function (err, font) {
    if (err) {
        alert('Could not load font: ' + err);
    } else {
        // Use your font here.
        console.log("loaded the font",font);
    }
});

produces the error:

▶ node test2.js

module.js:340
throw err;
^
Error: Cannot find module 'opentype'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (/Users/josh/projects/play/fonttest/test2.js:1:78)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)

The package.json does not have a 'main' property in it. If I add one to src/opentype.js I get errors about goog being missing.

Does opentype.js really work with node?

Improve energy conservation when attaching to the track

In EnergySkateParkBasicsModel.interactWithTracksWhileFalling when the skater attaches to the track, it computes uD from the bead-on-a-wire equations. We could take the additional step of correcting this value through search based on energy conservation, if necessary. I guess we will know if this work is necessary if energy is not conserved when the skater is attaching to the track.

Performance improvements for EnergySkateParkBasicsModel.step subdivisions

This todo came from the code:

For dt subdivision, make sure not updating any view code. Just update a model structure for numDivisions times, then update all views only once.

This will be a significant refactor and we should make sure it is worthwhile. It may also be difficult to estimate the benefit we may obtain from this (maybe not too much if scenery already postponing most events to updateScene).

Should the skater travel along the ground?

In the original Java Energy Skate Park: Basics, if the skater hits the ground, he will travel along the ground as if it has no friction. I thought it would make more sense for the skater to stop and remain motionless (as if it is grass), so that he doesn't escape from the screen. I don't think it would be too much work to add support for moving along the ground but thought I'd ask whether not we should add it before doing so.

Refactor to support different renderer

At the moment the code is hard coupled to render on the canvas object. So for example in Path.prototype.drawPoints, the Path geometry knows how to render itself on a canvas. Instead there should be a renderer, that knows how to draw a path on it self. This way its easier to support other renderer for example for SVG or OPENGL.

Also the renderer should be part of another module so the code can also be used without the renderer.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.