Using Google Font API to Render Inconsolata in HTML5 Canvas

In Contrasaurus we wanted some cooler fonts to add some extra ambiance to the game. I knew that adding a custom font from Google Font API was easy for classic HTML elements, but would it be easy for HTML5 Canvas elements? 5 minutes later I knew the answer… Yes!

// In the <head> tag
<link href='http://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' type='text/css'>
 
// In your js code
context.font = "bold 1.2em 'Inconsolata'";

4 thoughts on “Using Google Font API to Render Inconsolata in HTML5 Canvas

  1. Thanks for this piece – I’ve been trying to figure out how to embed Google fonts for a while. However, if does not seem to be working for me (see here: http://aterrell-www.cs.wisc.edu/search/test.html) Do you have some example that I can look at, or do you know if it doesn’t render properly in certain browsers? I’m running Firefox 4.

  2. Hmm, I think you’re right. I had also installed the Incosolata font around the same time I was experimenting, so it picked it up from the local system, but not from the CSS embed. I’ll need to look into this further and see if I can find out anything.

  3. Font face is loaded asynchronously. Even if it works in your Webpage it is not guaranteed that it will work in your Canvas via JavaScript. In most cases it will not work.
    Wrapping the rendering of your font with “window.onload = function() { // your ctx.font, ctx.fillText… etc }” will do the trick.

  4. That’s true! I had assumed that people would be rendering repeatedly in some kind of event loop, but I forgot about the standard case of just rendering once on page load. Thanks for the tip.

Leave a Reply

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