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

There are a few ways to do it theres the getImageData and putImageData methods Reference, However putImageData and getImageData are pretty slow. Another way is to save the data to an image in memory and recall it from that which is much faster, then the third way is the one above mentioned by andrewmu which involves copying to another canvas element. I have included examples for the first and second type.

Image in memory method

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    savedData = new Image();

function save(){
    // get the data
    savedData.src = canvas.toDataURL("image/png");
}

function restore(){
    // restore the old canvas
    ctx.drawImage(savedData,0,0)
}

getImageData putImageData method

// Setup our vars, make a new image to store the canvas data
var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    canvasData = '';

function save(){
    // get the data
    canvasData = ctx.getImageData(0, 0, 100, 100);
}

function restore(){
    // restore the old canvas
    ctx.putImageData(canvasData, 0, 0);
}