How to use fontkit - 10 common examples

To help you get started, we’ve selected a few fontkit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github assetgraph / assetgraph / lib / transforms / subsetFonts.js View on Github external
fontUsage.props['font-display'] = fontDisplay;
        }
      }
    }

    // Generate codepoint sets for original font, the used subset and the unused subset
    for (const htmlAssetTextWithProps of htmlAssetTextsWithProps) {
      for (const fontUsage of htmlAssetTextWithProps.fontUsages) {
        const originalFont = assetGraph.findAssets({
          url: fontUsage.fontUrl
        })[0];
        if (originalFont.isLoaded) {
          let originalCodepoints;
          try {
            // Guard against 'Unknown font format' errors
            originalCodepoints = fontkit.create(originalFont.rawSrc)
              .characterSet;
          } catch (err) {}
          if (originalCodepoints) {
            const usedCodepoints = fontUsage.text
              .split('')
              .map(c => c.codePointAt(0));
            const unusedCodepoints = originalCodepoints.filter(
              n => !usedCodepoints.includes(n)
            );

            fontUsage.codepoints = {
              original: originalCodepoints,
              used: usedCodepoints,
              unused: unusedCodepoints
            };
          }
github svgdotjs / svgdom / utils / textUtils.js View on Github external
fontFamily = families[i]
      break
    }
  }

  if (!fontFamily) {
    fontFamily = defaults.fontFamily
  }

  if (details.preloaded[fontFamily]) {
    font = details.preloaded[fontFamily]
  } else {
    let filename = path.join(fontDir, fontMap[fontFamily])

    try {
      font = fontkit.openSync(filename)
    } catch (e) {
      console.warn(`Could not open font "${fontFamily}" in file "${filename}". ${e.toString()}`)
      return new Box()
    }

    details.preloaded[fontFamily] = font
  }

  var fontHeight = font.ascent - font.descent
  var lineHeight = fontHeight > font.unitsPerEm ? fontHeight : fontHeight + font.lineGap

  var height = lineHeight / font.unitsPerEm * fontSize
  var width = font.layout(text).glyphs.reduce((last, curr) => last + curr.advanceWidth, 0) / font.unitsPerEm * fontSize

  // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor
  var xAdjust = 0
github devongovett / apple-color-emoji / build.js View on Github external
function getFont() {
  if (fs.existsSync(collectionPath)) return fontkit.openSync(collectionPath).fonts[0]; // both fonts in the collection seem to be identical
  if (fs.existsSync(fontPath)) return fontkit.openSync(fontPath);
  console.log('Could not find the emoji font');
  return null;
}
github devongovett / apple-color-emoji / build.js View on Github external
function getFont() {
  if (fs.existsSync(collectionPath)) return fontkit.openSync(collectionPath).fonts[0]; // both fonts in the collection seem to be identical
  if (fs.existsSync(fontPath)) return fontkit.openSync(fontPath);
  console.log('Could not find the emoji font');
  return null;
}
github sidorares / ntk / examples / fontkit.js View on Github external
async function main() {
  const app = await ntk.createClient();
  const window = app.createWindow();
  window.map();
  window.setActions();

  //const path =
  //  '/usr/share/texlive/texmf-dist/fonts/truetype/huerta/alegreya/AlegreyaSans-LightItalic.ttf';
  //const path = '/usr/share/fonts/truetype/ubuntu/Ubuntu.ttf';

  //const path = 'PT-Serif.woff2';
  const path = 'LibreBaskerville.woff2';
  var font = fontkit.openSync(path);

  // layout a string, using default shaping features.
  // returns a GlyphRun, describing glyphs and positions.
  var run = font.layout(
    'Simp' //lifies a 2D polyline, first using a radial distance check, and then a recursive Douglas-Peucker algorithm.'
  );

  //console.log(run);
  let size = 900;

  const ctx = window.getContext('2d');
  const _update = () => {
    let left = 0;
    let scale = size / 2048;
    const svgs = run.glyphs.map((g, index) => {
      var path = g.path.scale(scale, -scale).translate(10 + left * scale, 800);
github Munter / subfont / lib / subsetFonts.js View on Github external
htmlAsset: htmlAsset.urlOrDescription,
        fontUsages: fontUsages
      }))
    };
  }

  // Generate subsets:
  await getSubsetsForFontUsage(assetGraph, htmlAssetTextsWithProps, formats);

  // Warn about missing glyphs
  const missingGlyphsErrors = [];

  for (const { htmlAsset, fontUsages } of htmlAssetTextsWithProps) {
    for (const fontUsage of fontUsages) {
      if (fontUsage.subsets) {
        const characterSet = fontkit.create(Object.values(fontUsage.subsets)[0])
          .characterSet;

        for (const char of [...fontUsage.pageText]) {
          // Turns out that browsers don't mind that these are missing:
          if (char === '\t' || char === '\n') {
            continue;
          }

          const codePoint = char.codePointAt(0);

          const isMissing = !characterSet.includes(codePoint);

          if (isMissing) {
            let location;
            const charIdx = htmlAsset.text.indexOf(char);
github assetgraph / assetgraph / lib / util / fonts / downloadGoogleFonts.js View on Github external
});

      fontRelation.node.each(decl => {
        if (decl.prop !== 'src') {
          result[decl.prop] = decl.value;
        }
      });

      return [fontRelation.to, fontRelation.format];
    })
  );

  if (!('unicode-range' in result)) {
    const font = result.src[0][0];
    result['unicode-range'] = unicodeRange(
      fontkit.create(font.rawSrc).characterSet
    );
  }

  result['font-display'] = fontDisplay;

  // Output font face declaration object as CSS
  const declarationStrings = [];

  for (const [property, value] of Object.entries(result)) {
    if (property !== 'src') {
      declarationStrings.push(`  ${property}: ${value};`);
    }
  }

  const sources = result.src.map(([font, format]) => {
    return `url('${font.dataUrl}') format('${format}')`;
github qti3e / slye / core / three / font.ts View on Github external
private async ensure(): Promise {
    if (this.font) return;
    const data = await this.file.load();
    const buffer = new Buffer(data); // WTF! I don't like Buffer.
    this.font = fontkit.create(buffer);
  }
github assetgraph / assetgraph / lib / transforms / subsetFonts.js View on Github external
};
          }
        }
      }
    }

    // Generate subsets:
    await getSubsetsForFontUsage(assetGraph, htmlAssetTextsWithProps, formats);

    // Warn about missing glyphs
    const missingGlyphsErrors = [];

    for (const { htmlAsset, fontUsages } of htmlAssetTextsWithProps) {
      for (const fontUsage of fontUsages) {
        if (fontUsage.subsets) {
          const characterSet = fontkit.create(fontUsage.subsets.woff)
            .characterSet;

          for (const char of [...fontUsage.pageText]) {
            // Turns out that browsers don't mind that these are missing:
            if (char === '\t' || char === '\n') {
              continue;
            }

            const codePoint = char.codePointAt(0);

            const isMissing = !characterSet.includes(codePoint);

            if (isMissing) {
              let location;
              const charIdx = htmlAsset.text.indexOf(char);
github qooxdoo / qooxdoo-compiler / source / class / qx / tool / compiler / app / WebFont.js View on Github external
__processFontFile : function(filename, resolve, reject) {
      fontkit.open(filename, null, function(err, font) {
        if (err) {
          reject(err);
          return;
        }

        let resources = {};

        // If we have a mapping file, take this information instead
        // of anaylzing the font.
        if (this.getMapping()) {
          let mapPath = path.join(this.__library.getRootDir(), path.join(this.__library.getResourcePath(), this.getMapping()));
          fs.readFile(mapPath, {encoding: "utf-8"}, (err, data) => {
            if (err) {
              log.error(`Cannot read mapping file '${mapPath}': ${err.code}`);
              reject(err);
              return;

fontkit

An advanced font engine for Node and the browser

MIT
Latest version published 4 months ago

Package Health Score

78 / 100
Full package analysis