A neat trick with the HTML 5 canvas element in JavaScript is to use a second canvas to draw your canvas of screen, and flip it to a main canvas (examples include JQuery):
/* Prepare your canvas */
mainCanvas = $('#myCanvas');
offscreenCanvas = document.createElement('canvas');
/* Make sure your offscreen size matches your on screen
* size */
offscreenCanvas.width = mainCanvas.width;
offscreenCanvas.height = mainCanvas.height;
/* Do some drawing on the offscreen canvas */
ctxOffscreen = offscreenCanvas.getContext('2d');
ctxOffscreen.strokeRect(0, 0, 10, 10);
/* Now flip the offscreen canvas to the onscreen
* one */
ctxMain = mainCanvas.getContext('2d');
ctxMain.drawImage(offscreenCanvas, 0, 0);
And then your done. Whats nice about this, is its a good technique for creating flicker-reduced animations so you can prepare your next screen and 'flip' it when ready. The actually copy is done in hardware in most browsers so its quite performant.
Whats really nice about this concept, is that one can use 'drawImage' to overlay multiple offscreen canvases onto a single canvas. Combined with the use of alphas (transparency) you can create layers to a scene at separate stages and combine them at 'paint' time to be displayed on the onscreen canvas. Quite cool really.
Another technique I've heard about but never really used is to prepare 2 canvases and change the visibility:
/* Lets presume you already have two canvases with
* absolute layouts in the same place */
firstCanvas = $('#firstCanvas');
firstCanvas.css('display', 'block');
secondCanvas = $('#secondCanvas');
secondCanvas.css('display', 'none'); // hidden like a ninja
/* Do some drawing on the 'hidden' canvas */
ctxSecond = firstCanvas.getContext('2d');
ctxSecond.strokeRect(0, 0, 10, 10);
/* Now flip the two canvases, display one and hide the
* other */
firstCanvas.css('display', 'none');
secondCanvas.css('display', 'block');
I can't speak for the performance gain of this second methodology, but I can see it might have its advantages. Most conversations around double buffering suggest a technique like this, so its probably worth investigating.
No comments:
Post a Comment