Double buffering in <canvas> / javascript
Submitted by paul on Wed, 03/31/2010 - 17:23
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:
<div class="content"> <canvas id="canvas1" class="canvas" width="695" height="500"></canvas> <canvas id="canvas2" class="canvas" width="695" height="500"></canvas> </div>
Add styling to make them appear on top of each other:
.canvas { position: absolute; left: 0; top: 0; width: 695px; height: 500px; } #canvas1 { z-index: 100; } #canvas2 { z-index: 50; }
notice position absolute for canvas, so both appear on top of each other, and z-indexing.
javascript initialization:
game.currentCanvas = 1; game.canvas1 = document.getElementById('canvas1'); game.canvas2 = document.getElementById('canvas2'); game.context1 = g_game.canvas1.getContext('2d'); 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:
var oldCanvas = this.currentCanvas == 1 ? this.canvas1 : this.canvas2; this.currentCanvas = this.currentCanvas == 1 ? 2 : 1; var canvas = this.currentCanvas == 1 ? this.canvas1 : this.canvas2; var context = this.currentCanvas == 1 ? this.context1 : this.context2; context.clearRect(0, 0, this.width, this.height); // more drawing in context // brings current canvas to front and takes the old one to the back canvas.style.zIndex = 100; oldCanvas.style.zIndex = 0;
»
- paul's blog
- Login or register to post comments
