1

(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 and font by using
ctx.font = '20px myCustomFont'; ctx.fillText('Hello World', 150, 250);

it will resize to 20px but it only displays the default font. I am not sure what to do, here's the relevant code:

My CSS:

* {
  font-family: 'myCustomFont';
}
@font-face {
  font-family: 'myCustomFont';
  src: url('myCustomFont.ttf');

My HTML:

<p>This uses the custom font perfectly fine</p>
<canvas id='canvas' width='800' height='400'></canvas>

My JavaScript:

let ctx = document.getElementById('canvas').getContext('2d');
ctx.font = "20px myCustomFont";
ctx.fillText('Hello World', 150, 250); //Hello World will be at 20px, but it wont use the custom font
Ren 1 8 3
  • 13
  • 2
  • Does this answer your question? [How can I use custom fonts in an HTML5 Canvas element?](https://stackoverflow.com/questions/2608022/how-can-i-use-custom-fonts-in-an-html5-canvas-element) – Chin. Udara May 23 '21 at 04:25

1 Answers1

0

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 = new FontFace('myCusomFont', 'url(myCustomFont.ttf)');

f.load().then(function() {
  // Ready to use the font in a canvas context
  let 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.

A Haworth
  • 30,908
  • 4
  • 11
  • 14