I have a little problem with the context.fillText() function.
When I call a function using it, it doesn’t draw the text, unless I call it after I start the “mainloop”. All the context.fillRect()s called in the same function work perfectly.
Here is my code. I write a couple of comment to highlight where it works or doesn’t work.
var pause = true;
function draw () {
if ( !pause ) {
redraw_everything();
}
else {
draw_popup(); // WORKAROUND
}
}
function draw_popup ( text ) {
ctx.fillStyle = 'red';
ctx.fillRect ( _x, _y, _w, _h );
ctx.fillStyle = 'black';
ctx.fillRect ( _in_x, _in_y, _in_w, _in_h );
ctx.font = theight + "pt Orbitron";
twidth = ctx.measureText ( text ).width;
ctx.fillStyle = 'red';
ctx.fillText ( text, _tx, _ty ); /** Draw the text */
ctx.restore();
}
function init() {
canvas = document.getElementById ( 'tutorial' );
ctx = canvas.getContext ( '2d' );
pause = false;
draw();
pause = true;
setInterval ( 'draw()', 20 );
draw_popup ( 'PacMan' ); // DOESN'T WORK
tutorial = document.getElementsByTagName( 'body' )[ 0 ];
tutorial.onkeypress = function ( e ) {
var c = String.fromCharCode( e.charCode ).toLowerCase();
if ( c == 'p' ) {
draw_popup ( 'Pause' ); // IT WORKS
}
}
}
You can find the full source code here
UPDATE: As requested, I made a shorter example (not tested).
I found the problem. I am using a font from the Google Webfont collection. The first time i use it, the font isn’t loaded yet, so it doesn’t write. The following requests have the font already loaded, therefore i work