HTML5 Canvas filltext and font-face

Looking back at stackoverflow and google for ways to solve this problem, I had enough luck in the solution.

What happens is font font does not load at the right time. I have html5 canvas and javascript where I draw some simple circles with fill text inside them. Now the circles are drawn, but the text itself is the wrong font.

I assume the reason is that the font is loaded last and it just selects the default font.

Now I have a question ... is there a way so that I can delay the canvas objects drawn before the font was loaded? This way, the font will be ready for use, and it will assign the correct fonts to the canvas objects.

I should point out that I have an index.php file that includes my other php file where javascript and canvas are actually drawn.

+6
source share
2 answers

Use this trick and bind the onerror event to the Image element.

Demo here: http://jsfiddle.net/g6LyK/ - works with the latest Chrome.

 var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'http://fonts.googleapis.com/css?family=Vast+Shadow'; document.getElementsByTagName('head')[0].appendChild(link); // Trick from /questions/73200/javascript-capturing-load-event-on-link var image = new Image; image.src = link.href; image.onerror = function() { ctx.font = '50px "Vast Shadow"'; ctx.textBaseline = 'top'; ctx.fillText('Hello!', 20, 10); }; 
+4
source

According to the answer to this question, you may need to listen to onreadystatechange , checking if document.readystate === 'complete' is valid.

0
source

Source: https://habr.com/ru/post/901917/


All Articles