Does HTML5/Canvas Support Double Buffering?

Shai UI picture Shai UI · May 8, 2010 · Viewed 67.6k times · Source

What I'd like to do is draw my graphics on a buffer and then be able to copy it as is to the canvas so I can do animation and avoid flickering. But I couldn't find this option. Anyone know how I can go about this?

Answer

Fedor van Eldijk picture Fedor van Eldijk · May 19, 2010

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