Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to clone HTML5 canvas element with its content?

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

like image 246
Evgenyt Avatar asked Jul 23 '10 13:07

Evgenyt


People also ask

How do I clone a canvas in JavaScript?

Cloning a canvas and rendering itThe clone() method receives a callback function as the first argument within which we are converting our cloned canvas object into JSON. This new cloned canvas object is now overwritten onto the canvas.

How do I save my element in canvas?

You can save a canvas to an image file by using the method canvas. toDataURL() , that returns the data URI for the canvas' image data. The method can take two optional parameters canvas.


2 Answers

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.

like image 55
Robert Hurst Avatar answered Sep 22 '22 03:09

Robert Hurst


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

like image 40
Castrohenge Avatar answered Sep 21 '22 03:09

Castrohenge