Javascript 有什么方法可以克隆 HTML5 画布元素及其内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3318565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Any way to clone HTML5 canvas element with its content?
提问by Evgenyt
Is there any way to create a deepcopy of a canvas element with all drawn content?
有没有办法用所有绘制的内容创建一个画布元素的深层副本?
回答by Robert Hurst
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.
使用 getImageData 用于像素数据访问,而不是用于复制画布。在浏览器上使用它进行复制非常缓慢且困难。应该避免。
回答by Castrohenge
You can call
你可以打电话
context.getImageData(0, 0, context.canvas.width, context.canvas.height);
which will return an ImageData object. This has a property named dataof 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.
这将返回一个 ImageData 对象。它有一个名为data的属性,类型为 CanvasPixelArray,其中包含所有像素的 rgb 和透明度值。这些值不是对画布的引用,因此可以在不影响画布的情况下进行更改。
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
如果您还需要该元素的副本,则可以创建一个新的 canvas 元素,然后将所有属性复制到新的 canvas 元素中。之后,您可以使用
context.putImageData(imageData, 0, 0);
method to draw the ImageData object onto the new canvas element.
方法将 ImageData 对象绘制到新的画布元素上。
See this answer for more detail getPixel from HTML Canvas?on manipulating the pixels.
请参阅此答案以获取更多详细信息getPixel from HTML Canvas?关于操作像素。
You might find this mozilla article useful as well https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Drawing_shapes
您可能会发现这篇 mozilla 文章也很有用https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Drawing_shapes

