Displaying Custom Fonts in HTML5 Canvas

In some browsers custom fonts will not display on the canvas unless they are also rendered somewhere on the page. This is because the browser will not bother to download the custom font file unless it believes it will definitely need it. The browser doesn’t know what fonts will be required by the canvas until it sees the text element created and by that time it is too late.

There are two ways to fix this problem. The first way is the most simple and involves creating a HTML element somewhere on the page that uses the font.

Make sure sure to not use display:none and instead use visibility: hidden. Using display:none will cause the same issue where the browser believes that the font is not being used. I’m also using the same color as the background as a fallback. Your custom @fontface fonts should now display properly in the canvas.

Do you require dynamic font loading?

In a recent project I not only needed to use custom fonts on canvas, but the project required that they be dynamically loaded at runtime instead of on page load. I accomplished this by using a library called Web Font Loader, which is developed by Google and Typekit. It provides many font related features, but the one we are most interested is in the dynamic loading of custom fonts, which you can read about here: Custom fonts.

1 thought on “Displaying Custom Fonts in HTML5 Canvas”

Leave a Reply

Your email address will not be published. Required fields are marked *