if I draw to the canvas a lot in quick succession, e.g. a context.fillRect in a loop, browsers seem to wait until the loop has finished before any of the drawing is displayed (possibly via double-buffering)
Is there any way to force the browser to update the display, either explicitly or implicitly after each draw operation?
It is not really because of any double-buffering that you don't see the results, but rather because JavaScript in the web browser is single-threaded. If you similarly create a single loop in JavaScript that repeatedly does something like myDiv.style.top = parseInt(myDiv.style.top) + 1 +"px";
you will see that nothing will visibly change in the browser—even over many seconds—until your JavaScript has finished executing.
To draw changes and see the results on the screen, you need to use setInterval
or setTimeout
to yield control back to the browser but ask to run code at some point in the future.
For example, to draw a new random, randomly-colored rectangle on the canvas 15 times a second:
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
setInterval(function(){
ctx.clearRect(0,0,canvas.width,canvas.height);
var r=Math.random()*255, g=Math.random()*255, b=Math.random()*255;
ctx.fillStyle = 'rgb('+r+','+g+','+b+')';
var w=Math.random()*canvas.width, h=Math.random()*canvas.height;
var x=Math.random()*(canvas.width-w), y=Math.random()*(canvas.height-h);
ctx.fillRect(x,y,w,h);
},1000/15);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With