how to force a display update in canvas

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);

Tags:

Html

Canvas