Manngo
Manngo

Reputation: 16433

Getting the glyph width of a monospaced font

Recently I asked on a different forum about the glyph width of the Source Code Pro font (it’s 600). This helps me in setting tab stops in a word processor for code samples.

How do I find the glyph width of other Monospaced fonts?

Upvotes: 0

Views: 170

Answers (1)

herrstrietzel
herrstrietzel

Reputation: 17334

You can retrieve font metrics using opentype.js

Once the font file is parsed, you can easily check many glyph or font properties against the retrieved objects:

let glyph = font.charToGlyph('m');
let glyphWidth = glyph.advanceWidth;

So far opentype.js does not support woff2 files.

Support for WOFF, OTF, TTF (both with TrueType glyf and PostScript cff outlines)

You can use google webfont helpers api to fetch woff or truetype files.

Since some webfonts use 2048 units per em, you might calculate a normalized glyph width (relative to 1000 units per em):

//source code pro (1000 units per em)
let fontURL0 =
  "https://fonts.gstatic.com/s/sourcecodepro/v22/HI_diYsKILxRpg3hIP6sJ7fM7PqPMcMnZFqUwX28DMyQtMlrSg.woff";

//open sans (2048 units per em)
let fontURL1 =
  "https://fonts.gstatic.com/s/opensans/v29/memSYaGs126MiZpBA-UvWbX2vVnXBbObj2OVZyOOSr4dVJWUgsjZ0B4gaVQ.woff";

getFontMetrics(fontURL0, "m", spanGlyphWidth0);
getFontMetrics(fontURL1, "m", spanGlyphWidth1);

function getFontMetrics(fontURL, char, span) {
  opentype.load(fontURL, function(err, font) {
    let unitsPerEm = font.unitsPerEm;
    let em1000Ratio = 1000 / unitsPerEm;
    let glyph = font.charToGlyph(char);
    let glyphWidth = glyph.advanceWidth;
    let glyphWidthRelative = +glyphWidth * em1000Ratio.toFixed(1);
    let fontName = font.tables.name.fullName.en;
    //console.log(font)
    span.textContent = `"${fontName}" – unitsPerEm: ${unitsPerEm} | width (absolute): ${glyphWidth} | width (relative to 1000 units/em): ${glyphWidthRelative} `;
  });
}
<script src="https://cdn.jsdelivr.net/npm/opentype.js@latest/dist/opentype.min.js"></script>

<p><span id="spanGlyphWidth0"></span></p>
<p><span id="spanGlyphWidth1"></span></p>

Upvotes: 0

Related Questions