HTML5 Canvas filltext and font-face

2019-02-17 08:09发布

Been looking around stackoverflow and google for ways to solve this issue im having but havent had much luck with a solution.

What is happening is my font-face font is not loading at the right time. What I have going on is I have a html5 canvas and javascript where I am drawing some simple circles with fill text inside them. Now the circles are getting drawn but the text itself is the wrong font.

I'm assuming the reason being is because the font is being loaded last and it just picks the default font.

Now my question is... is there a way I can delay the canvas objects being drawn until the font is loaded? This way the font will be ready to use and it will assign the right fonts to the canvas objects.

I should point out that I have a index.php file that includes my other php file where the javascript and canvas is actually being drawn.

2条回答
劳资没心,怎么记你
2楼-- · 2019-02-17 08:49

According to an answer to this question, you might need to listen to the onreadystatechange event, checking if document.readystate === 'complete'.

查看更多
祖国的老花朵
3楼-- · 2019-02-17 08:52

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

Demo here: http://jsfiddle.net/g6LyK/ — works on 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 https://stackoverflow.com/questions/2635814/
var image = new Image;
image.src = link.href;
image.onerror = function() {
    ctx.font = '50px "Vast Shadow"';
    ctx.textBaseline = 'top';
    ctx.fillText('Hello!', 20, 10);
};
查看更多
登录 后发表回答