Any way to clone HTML5 canvas element with its content?

JavascriptHtmlCanvasClone

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 https://stackoverflow.com/questions/667045/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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEvgenytView Question on Stackoverflow
Solution 1 - JavascriptRobert HurstView Answer on Stackoverflow
Solution 2 - JavascriptCastrohengeView Answer on Stackoverflow