Any way to clone HTML5 canvas element with its content?

Evgenyt picture Evgenyt · Jul 23, 2010 · Viewed 50k times · Source

Is there any way to create a deep copy of a canvas element with all drawn content?

Answer

Robert Hurst picture Robert Hurst · Nov 29, 2011

Actually the correct way to copy the canvas data is to pass the old canvas to the new blank canvas. Try this function.

function cloneCanvas(oldCanvas) {

    //create a new canvas
    var newCanvas = document.createElement('canvas');
    var context = newCanvas.getContext('2d');

    //set dimensions
    newCanvas.width = oldCanvas.width;
    newCanvas.height = oldCanvas.height;

    //apply the old canvas to the new one
    context.drawImage(oldCanvas, 0, 0);

    //return the new canvas
    return newCanvas;
}

Using getImageData is for pixel data access, not for copying canvases. Copying with it is very slow and hard on the browser. It should be avoided.