0

I am unable to load fonts to use in canvas. I have font file OpenSans-Regular.ttf in same folder as html.

<style>
@font-face {
    font-family: 'OpenSans';
    src: url(OpenSans-Regular.ttf) format("truetype");
}
</style>

<canvas id="c" width="1000" height="1400"></canvas>


<script>

var c = document.getElementById("c").getContext('2d');

c.font = '100px OpenSans';
c.fillText('Loading...', 110, 110);

</script>

This does load the font (in Debugger/Network), but isnt used on canvas. If I replace src: url(OpenSans-Regular.ttf) with local('OpenSans-Regular.ttf') it doesnt even load in Debugger/Network. I tried adding/removing the quotes in both ways, tried removing and adding the .ttf. But nothing worked.

NOTE: I some of these tries I was sure the font is properly loaded, and can use it in other element.

Thank you

Makalone LOgman
  • 948
  • 1
  • 12
  • 25
  • 1
    Possible duplicate of [Drawing text to with @font-face does not work at the first time](https://stackoverflow.com/questions/2756575/drawing-text-to-canvas-with-font-face-does-not-work-at-the-first-time) – Daniel A. White Feb 20 '19 at 16:07

1 Answers1

1

If you are seeing the font file within the debugger, your code for the canvas is probably running before the font has been loaded.

You can read more in this answer to the possible duplicate question Daniel White mentioned: https://stackoverflow.com/a/7289880/864799

Instead of the WebFontLoader, you might want to use the more recent FontFaceObserver, by the same maintainer.

For example:

<style>
@font-face {
    font-family: 'Example';
    src: url('Example-Regular.woff2') format('woff2');
}
</style>

<canvas id="c" width="1000" height="1400"></canvas>

<!-- You could also include this locally, but this is the latest version at the time of writing. -->
<script src="https://unpkg.com/fontfaceobserver@2.1.0/fontfaceobserver.standalone.js"></script>
<script>

var c = document.getElementById("c").getContext('2d');

var font = new FontFaceObserver('Example', {
  weight: 400
});

font.load().then(function () {
  console.log('Font is available');

  c.font = '100px Example';
  c.fillText('Loading...', 110, 110);  

}, function () {
  console.log('Font is not available');
});
</script>

You can find more detailed examples in the FontFaceObserver README.

kennethormandy
  • 2,080
  • 14
  • 16