Makalone LOgman
Makalone LOgman

Reputation: 980

Unable to load font to canvas

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

Upvotes: 0

Views: 1918

Answers (1)

kennethormandy
kennethormandy

Reputation: 2160

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/[email protected]/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.

Upvotes: 2

Related Questions