In rare cases, <canvas> does not redraw

I use <canvas> to draw all notes and glyphs in my music educational web apps: http://www.musictheory.net/exercises/keysig/bc98yy

A Firefox user 15.0.1 reported that sometimes the exercise continues to the next question, but the previous question is still displayed on the canvas. I saw how this happens when testing once (out of ~ 500 questions).

When this happens, the canvas was cleared using canvas.width = canvas.width and calling .clearRect in context, and glyphs were drawn in JavaScript via .beginPath , .quadraticCurveTo , .closePath , etc. However, it seems that the canvas support buffer never lights up / draws into the window.

I have seen error messages in the past regarding similar issues:

I can make it redraw by hacking the DOM, for example, inserting the text node as a child of the canvas and then deleting it in the next cycle of the run cycle or changing the background color or filling the canvas. It seems hard, however, and I always get the feeling the nagging that I'm missing something obvious.

My drawing code is quite simple:

 canvas.width = width; ctx.clearRect(0, 0, width, height); ctx.save(); // Lots of drawing code here ctx.restore() ctx.clearRect(0, 0, 1, 1); // Helped force a repaint on some older WebKit browsers? 

I am sure the number of calls to .save and .restore balanced.

1) I call this code directly in response to the onclick event handler. Should I use requestAnimationFrame or setTimeout to execute the drawing in the next run cycle loop?

2) I won’t miss something obvious, like the canvas.pleaseRepaintNow() API, right?

3) Did other people have similar problems and resorted to modifying the DOM to force redrawing?

+8
javascript canvas redraw
source share
2 answers

Add context.stroke(); to the last line of your onLoad function, it fixes a bug in Firefox. Otherwise, changes to the canvas are not displayed until the window is redrawn.

In my case, it worked at least.

 window.onload = function() { canvas = document.getElementById("canvas"); context = canvas.getContext("2d"); //Code here... context.stroke(); } 
+4
source share

I tried to get an error, but after a crazy click on Firefox for a while I did not see it. This is how I clean the canvas, which seems to work, but take it with salt because I cannot get the error. I also cannot check if something is fixed ...

 // Store the current transformation matrix ctx.save(); // Use the identity matrix while clearing the canvas ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, canvas.width, canvas.height); // Restore the transform ctx.restore(); 
+1
source share

All Articles