Day 6 – Getting canvas in on the web fonts fun

It’s no secret that canvas leaves a lot to be desired when it comes to even the most basic typography. But at least we can still use more than just the usual web safe font suspects! This installment of our snack-sized tips is all about how to use your web font(s) of choice in canvas reliably.

Just like any content, fonts need to load before you can use them. If you want to be absolutely sure that your fonts are there, or want better control over what happens if they’re not, your best bet is using font events.

My web font service of choice, Typekit, provides a font loading events system that makes this extra easy. Turns out they’re also nice folks and have open sourced this system as the Google WebFont Loader. So you can use this technique no matter how you prefer to source your web fonts. Something for everyone! It is Christmas, after all :)

We’re going to take advantage of the same font events that are usually used to prevent the FOUT (Flash Of Unstyled Text) to delay our call to fillText() until we know our web fonts are available. If we call fillText() before our font has loaded we’ll get a lovely line default serif text instead. That could really mess things up.

Let’s look at what it takes to create this simple example of displaying a line of text in Proxima Nova Soft in canvas. For the sake of simplicity, this example assumes you’re using Typekit. (The Google WebFont Loader docs provide instructions on how to set up the API with other services.)

First, we need to add the code to listen for the active font event. That’s the one that fires when the font(s) are available for use. Then, set the displayText() function to be called when the active event is fired.

try {
     active: function() {
       // Javascript to execute when fonts become active
} catch(e) {}

So now, when the web fonts are active, my displayText() function will be called. In this basic example there’s really not much to it. I’m just telling my canvas to fillText with the parameters I’ve already defined:

function displayText() {
     dcontext.fillText(words, textOffsetLeft, textAscent);   

All the parameters for my font properties, including the reference to the web font, were assigned in my initial set up. I’ve used the shortform to define the weight, size, and font-family a few lines up from the displayText() function:

 dcontext.font = "400 162px proxima-nova-soft";

If you’re wondering, canvas uses font weights the same way CSS does (yay!). In this case, I’m using a font weight of 400 which corresponds to the regular weight of Typekit’s Proxima Nova Soft.

In this ever so slightly more complex example, I’ve increased the weight to 700 for Proxima Nova Soft Bold, and doubled up the text to create a bit of a drop shadow.

So there you have it. An easy tip for getting your favourite web fonts to play nice with canvas!