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  tag


// In your js code
context.font = "bold 1.2em 'Inconsolata'";
Unknown's avatar

Author: Daniel X

Heretic priest of the Machine God. I enjoy crawling around in Jeff Bezo's spaceship, bringing technology to the people, and long walks outside of time and space.

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

    1. 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.

      Like

  1. 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.

    Liked by 1 person

    1. 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.

      Like

Leave a reply to Daniel X Moore Cancel reply