Accurately Detect Web Font in Use

From time to time you browse a website and notice that it's using a very pleasing font, and the designer in you wants to know its name. To solve this problem, my friend Willow made a very nice utility called WhatFont a while ago. It's a bookmarklet (and later as Chrome/Safari extensions). Once activated, you can hover your mouse cursor on the text that you're interested in, and it will display the font name of the underlying text. If you click on it, a popover box will appear, showing detailed information like the complete font family, font size, line height, where the font comes from (if it's a web font from a few supported vendors), and a type specimen.

The problem is that CSS font-family property usually contains a list of type faces to fallback on and there is no easy way to know exactly which one of the them is actually used from the browser.

I fixed it using a dirty hack. Here is how it works.

First, it creates a hidden canvas element, and draw some text using the same list of typefaces from the font-family property (e.g. font-family:fontA, fontB, fontC, etc;). Then it creates another hidden canvas element, and draw the same text, but this time it tries each typeface individually (e.g. font-family: fontA;). Now it has two canvas elements with some text on them, and it compares the two pixel-by-pixel. If the two are identical pixel-wise, we can reasonably conclude that fontA is the one actually used.

This mechanism is not 100% reliable, but it works pretty well for our purpose. The source code of WhatFont is available on GitHub here.