Skip to content Skip to sidebar Skip to footer

How Come My Custom Font Wont Show When I Write Stuff With Filltext()?

(Note: I'm still kind of a beginner) I have a custom font that works fine for nearly all text on my page, but I have a canvas element that I want text on so I try to apply the size

Solution 1:

I've experienced this problem and it was down to the fact that at the time of writing the canvas the font wasn't loaded.

It wouldn't have been loaded to display the paragraph in your example either, but the system will go back and redisplay that once the font is fully loaded, and on modern systems that tends to be so quick that you don't even notice a flash of repainting. However by then it doesn't know that what you had drawn on the canvas was text, the canvas is just a bunch of 'pixels' as far as it is concerned.

MDN discusses the canvas font issue and has a recommendation for not drawing the canvas text until the font is loaded.

With the help of the FontFace API, you can explicitly load fonts before using them in a canvas.

let f = newFontFace('myCusomFont', 'url(myCustomFont.ttf)');

f.load().then(function() {
  // Ready to use the font in a canvas contextlet ctx = document.getElementById('canvas').getContext('2d');
  ctx.font = "20px myCustomFont";
  ctx.fillText('Hello World', 150, 250);
});

I guess you'd want to combine that with some check that the fontface does actually load within a reasonable time (for example, if the font server is outside your control could it be down?) and if not fall back to some font you know will be available.

Note: check caniuse that the API is supported by all the browsers you have to support. It is supported by Chrome/Edge, FF, Safari but not by IE so if you still need to support IE you'll need to sense that and add a workaround e.g. not drawing on the canvas until a timeout has expired.

Post a Comment for "How Come My Custom Font Wont Show When I Write Stuff With Filltext()?"