7

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.

Anks
  • 485
  • 9
  • 27
  • Been trying many different methods to get this to work but it just seems the font is still loading at the end of when the page loads. So the canvas filltext doesnt render with the right font. Any thoughts? – Anks Nov 20 '11 at 15:22

2 Answers2

5

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);
};
Community
  • 1
  • 1
a paid nerd
  • 30,702
  • 30
  • 134
  • 179
  • This works, but the way I have my javascript generating the canvas contents I cant seem to get it to work the way I need it to. I have an array with multiple strings and need to write each one to a new image on the canvas. Its going through a for loop. Any suggestions? – Anks Nov 27 '11 at 15:42
  • As long as your code is executed in the `image.onerror` callback you should be able to use the font. Try putting your loop inside there. – a paid nerd Nov 27 '11 at 17:51
0

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

Community
  • 1
  • 1
linqq
  • 3,067
  • 2
  • 19
  • 17