Any way to clone HTML5 canvas element with its content?

纵饮孤独 提交于 2019-12-17 02:47:27

问题


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


回答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.




回答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



来源:https://stackoverflow.com/questions/3318565/any-way-to-clone-html5-canvas-element-with-its-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!