Any way to clone HTML5 canvas element with its content?

Solution 1:

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.

Solution 2:

You can call

context.getImageData(0, 0, context.canvas.width, context.canvas.height);

which will return an ImageData object. This has a property named data of type CanvasPixelArray which contains the rgb and transparency values of all the pixels. These values are not references to the canvas so can be changed without affecting the canvas.

If you also want a copy of the element, you could create a new canvas element and then copy all attributes to the new canvas element. After that you can use the

context.putImageData(imageData, 0, 0);

method to draw the ImageData object onto the new canvas element.

See this answer for more detail getPixel from HTML Canvas? on manipulating the pixels.

You might find this mozilla article useful as well https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Drawing_shapes