Double buffering in <canvas> / javascript

I extracted this technique from http://www.gamesforthebrain.com/game/oooze/ . Unfortunatelly it is commented out in their code so I'll have to test it myself:

Declare 2 canvases in html something like this:

  1. <div class="content">
  2. <canvas id="canvas1" class="canvas" width="695" height="500"></canvas>
  3. <canvas id="canvas2" class="canvas" width="695" height="500"></canvas>
  4. </div>

Add styling to make them appear on top of each other:

  1. .canvas {
  2. position: absolute;
  3. left: 0;
  4. top: 0;
  5. width: 695px;
  6. height: 500px;
  7. }
  8.  
  9. #canvas1 {
  10. z-index: 100;
  11. }
  12.  
  13. #canvas2 {
  14. z-index: 50;
  15. }

notice position absolute for canvas, so both appear on top of each other, and z-indexing.

javascript initialization:

  1. game.currentCanvas = 1;
  2. game.canvas1 = document.getElementById('canvas1');
  3. game.canvas2 = document.getElementById('canvas2');
  4. game.context1 = g_game.canvas1.getContext('2d');
  5. game.context2 = g_game.canvas2.getContext('2d');

now in the draw() function, draw in the 'other' one , (ie not the current one) and flip them at the end:

  1. var oldCanvas = this.currentCanvas == 1 ? this.canvas1 : this.canvas2;
  2. this.currentCanvas = this.currentCanvas == 1 ? 2 : 1;
  3. var canvas = this.currentCanvas == 1 ? this.canvas1 : this.canvas2;
  4. var context = this.currentCanvas == 1 ? this.context1 : this.context2;
  5.  
  6. context.clearRect(0, 0, this.width, this.height);
  7. // more drawing in context
  8.  
  9. // brings current canvas to front and takes the old one to the back
  10. canvas.style.zIndex = 100;
  11. oldCanvas.style.zIndex = 0;