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'";
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.
LikeLike
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.
LikeLike
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.
LikeLiked by 1 person
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.
LikeLike