Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas filltext and font-face

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.

like image 798
Anks Avatar asked Nov 20 '11 02:11

Anks


1 Answers

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);
};
like image 55
a paid nerd Avatar answered Oct 19 '22 15:10

a paid nerd