Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the rendered font in JavaScript?

Google Chrome displays the rendered font in the DevTools.

For example, given:

font-family: Montserrat, Helvetica, sans-serif;

and the Montserrat font is missing/disabled, Chrome tells us that Helvetica is being rendered:

enter image description here

Is there a way to get the rendered font in JavaScript? (even if it just works in Chrome)


Notes:

  1. This solution suggests getComputedStyle(...).fontFamily, but it returns the CSS declaration "Montserrat, Helvetica, sans-serif", not the actual rendered font.
  2. This solution uses puppeteer, but I couldn't figure out how to achieve the same purely in DevTools (without puppeteer).
like image 889
Misha Moroshko Avatar asked Sep 09 '19 11:09

Misha Moroshko


1 Answers

It is still not possible to access this information from Web-APIs.

There is an ongoing discussion in the Houdini group about including a font-metrics API, that is supposed to include something like that, but it's still not even proposed as a spec draft and there will be a lot of burden on the road.

What font(s) are being used? This is complicated because multiple fonts can be used per paragraph, per line, per word, and even per glyph. The fonts should be exposed in the form of handles with complete font information, and (for web fonts) a handle to the raw font data. dbaron & eae are going to own this area and propose an API.

Indeed, one could have one font for the glyph ̂ (U+0302), and another one for the glyph a (U+0061) which would make the combined glyph would actually use two different fonts.

Current discussions seem to point to a Font interface available from document.measureElement and document.measureText methods. This interface would expose two properties: a DOMString name, and a number glyphsRendered. However, once again these are still discussion and still not yet proposed as drafts, a lot of discussion is still to be made and I wouldn't hold my breath waiting for it to be implemented anywhere any time soon.


Now, there are hacks, like numerous other Q/A already told don't stick to the accepted answer there, implying looking at the size of the rendering for the simplest, and looking at the rendered pixels for the more advanced ones, but being hacks, they won't work in every cases.
For instance, I could have a custom font on my system that would render only some characters borrowed from a well-known font, no such hack would be able to tell if the browser did fallback to that font or the actual well-known one.

The only way to know for sure is to keep the control and use web-fonts.

like image 89
2 revs Avatar answered Oct 07 '22 04:10

2 revs