html5: copy a canvas to image and back

The drawImage() method can draw to a canvas using another canvas instead of an image.

You could create a ‘backup’ canvas, of the same size as your original, draw the first one to there and then draw that one back to the original when you need it.

e.g.

// Assume we have a main canvas
// canvas = <main canvas>
ctx = canvas.getContext('2d');
..

// create backing canvas
var backCanvas = document.createElement('canvas');
backCanvas.width = canvas.width;
backCanvas.height = canvas.height;
var backCtx = backCanvas.getContext('2d');

// save main canvas contents
backCtx.drawImage(canvas, 0,0);

..

// restore main canvas
ctx.drawImage(backCanvas, 0,0);

Leave a Comment