I am developing a web page which uses <canvas>
elements and javascript to draw in them (visualising data, so I can't readily set up a jsfiddle). The user can interact with the plot, but due to the size of the datasets, sometimes the canvas can take 1-2 sec to redraw. So I want to give the user some visual clue that things are happening. In principle, I thought this was easy, I have something like this:
$('#myCanvas').css('opacity',0.5);
$('#myWorkingAnimatedGif').css('display','block');
updateMyCanvas();
The updateMyCanvas()
call look something like this
function updateMyCanvas()
{
// loop through data, drawing via paths
// takes 1-2 sec to run on big datasets
// no asynchronous calls, just for loops
$('#myCanvas').css('opacity',1);
$('#myWorkingAnimatedGif').css('display','none');
}
i.e. plot the data, then remove the "I am working" visual clues.
However, this is not working; what happens instead is that the user clicks to replot, nothing happens for 1-2 sec, and then the data are replotted. i.e. the css commands are not implemented by the browser until after it's drawn the canvas, at which point it hits the css commands to undo those changes. In fact, if I edit updateMyCanvas()
so that it does not restore the CSS to what it was, then when the user clicks, nothing happens for 1-2 sec, then the data replot and roughly simulataneously, the opacity changes and the animated gif appears.
On the other hand, if I instead do the following:
$('#myCanvas').css('opacity',0.5);
$('#myWorkingAnimatedGif').css('display','block');
window.setTimeout(function(){updateMyCanvas();}, 10);
It works fine, even though the 10ms timeout is around 1% of the time it takes updateMyCanvas()
to run.
Does anyone know why this is? It's as if the javascript engine simply doesn't process my jquery css operations until after it's done all the canvas drawing stuff. I've tried this on firefox and Chrome (both under Linux) so it's not related to one specific engine.