opentypejs / opentype.js

Read and write OpenType fonts using JavaScript.
https://opentype.js.org/
MIT License
4.51k stars 479 forks source link

Checking glyph names exist in a web font #480

Open BenRacicot opened 3 years ago

BenRacicot commented 3 years ago

Hello, I hope it's appropriate to ask here but I'm hoping someone has insight on how to best detect if a glyph exists within a font. This is very important for a font-icon setup on the web.

It seems that opentype,js can do this but it's awfully heavy for me to load in my app for something so simple.

Example: Check if a smiley glyph name exists in my icon-font

glyphExists('smiley') // returns boolean 

Thanks for any help you may have on this.

zbryikt commented 3 years ago

you probably need a table for looking up certain keyword for corresponding code point, like, with CLDR ( http://unicode.org/Public/cldr/39/ or https://github.com/unicode-org/cldr-json )

with this you can come up with something like codePointByKeyword().

Next you will need to list all supported code points:

    opentype.load("path-to-your-font").then(function(font) {
      var allcodes = [];
      for(var i=0; i < font.glyphs.length; i++) {
          allcodes = allcodes.concat(font.glyphs.glyphs[i].unicodes || []);
      }
      return allcodes;
    });

and then finally the glyphExists function:

function glyphExists(keyword) {
    return ~allcodes.indexOf(codePointByKeyword(keyword));
}

Yet codePointByKeyword probably should return array of codes so above is just an idea / concept for reference.

And since it needs CLDR from unicode.org, I think it probably should be implemented outside of opentype.js.