Any way to clone an HTML5 canvas element with its contents?

Is there a way to create a deep copy of the canvas element with the whole image?

+47
javascript clone html5 canvas
Jul 23 '10 at 13:31
source share
2 answers

In fact, the correct way to copy canvas data is to transfer the old canvas to a new blank canvas. Try this feature.

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 accessing pixel data, not for copying canvases. Copying with it is very slow and difficult in the browser. It should be avoided.

+86
Nov 29 '11 at 4:52
source share

You may call

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

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

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

 context.putImageData(imageData, 0, 0); 

to draw an ImageData object on a new canvas element.

See this getPixel answer from HTML Canvas for more details ? for pixel management.

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

+11
Jul 23 '10 at 16:16
source share



All Articles