Overview of the Code

As you can see, our code itself is pretty simple. You just need to know how to do some basic things with the HTML5 Canvas API. What may be less simple is the madness that our code represents and how it helps you figure out whether a font is available or not.

The way our code works is by taking advantage of the Canvas element and the APIs it provides for drawing and measuring the size of what you draw. First, I virtually draw two pieces of text.

One piece of text is drawn using a default monospace font:

widget

The code for this looks as follows:

context.font = "72px monospace";

The other piece of text is drawn using the font that you are interested in checking on along with the default monospace font in case that font doesn’t exist:

context.font = "72px '" + fontName + "', monospace";

Let’s walk through an example. For our example, we want to check whether the Corbel font can be used. Below is what our sample text using Corbel looks like:

widget

Now, here is the magic that helps us get what we want. I use the Canvas element’s measureText function to measure the size (in pixels) of both pieces of text. I store the size of our monospace text in a variable called baselineSize. I store the size of our text drawn using Corbel as newSize:

widget

Next, I check whether the sizes stored in baselineSize and newSize are the same or different. Now, why would I do this?

If the Corbel font exists on your system, then drawing some text using it will display using that font itself. This means that it has a size that depends on the parameters unique to Corbel. Similarly, your monospace text will display using a size that corresponds to the default monospace font used.

If the sizes of both are different, like you can see in the above image, this means that each piece of text is being displayed using a different font: monospace and Corbel. You wouldn’t get a different size if the font you are curious about does not exist. You would instead get both pieces of text displaying using the fallback monospace font…such as what you will see below:

widget

You will have two pieces of text displayed at the exact same pixel size. That is a dead giveaway that the font you are curious about doesn’t exist and the fallback font monospace font is being used instead.

Be Careful When Checking Actual Monospace Fonts

The only time you may get a false negative is when you actually specify a monospace font like Courier New or Consolas that is also set as the default monospace font for your browser. In such cases, your font will exist but it will also display in the same size as the text specified to display only as monospace. Using our current logic, this means that despite your font existing, the code will tell you otherwise.

I don’t envision these situations being too common, but do look out for that case.