Does HTML5/Canvas Support Double Buffering?

Browsers I've tested all handle this buffering for you by not repainting the canvas until the code that draws your frame has completed. See also the WHATWG mailing list: http://www.mail-archive.com/[email protected]/msg19969.html


The following helpful link, in addition to showing examples and advantages of using double buffering, shows several other performance tips for using the html5 canvas element. It includes links to jsPerf tests, which aggregate test results across browsers into a Browserscope database. This ensures that the performance tips are verified.

https://web.dev/canvas-performance/

For your convenience, I have included a minimal example of effective double buffering as described in the article.

// canvas element in DOM
var canvas1 = document.getElementById('canvas1');
var context1 = canvas1.getContext('2d');

// buffer canvas
var canvas2 = document.createElement('canvas');
canvas2.width = 150;
canvas2.height = 150;
var context2 = canvas2.getContext('2d');

// create something on the canvas
context2.beginPath();
context2.moveTo(10,10);
context2.lineTo(10,30);
context2.stroke();

//render the buffered canvas onto the original canvas element
context1.drawImage(canvas2, 0, 0);

You could always do var canvas2 = document.createElement("canvas"); and not append it to the DOM at all.

Just saying since you guys seem so obsessed with display:none; it just seems cleaner to me and mimicks the idea of double buffering way more accurately than just having an awkwardly invisible canvas.


A very simple method is to have two canvas-elements at the same screen location and set visibility for the buffer that you need to show. Draw on the hidden and flip when you are done.

Some code:

CSS:

canvas { border: 2px solid #000; position:absolute; top:0;left:0; 
visibility: hidden; }

Flipping in JS:

Buffers[1-DrawingBuffer].style.visibility='hidden';
Buffers[DrawingBuffer].style.visibility='visible';

DrawingBuffer=1-DrawingBuffer;

In this code the array 'Buffers[]' holds both canvas-objects. So when you want to start drawing you still need to get the context:

var context = Buffers[DrawingBuffer].getContext('2d');