简体   繁体   中英

Copy a canvas node from a jquery object not in the DOM tree

I have been working on a game engine for the last little while and I recently added what i call a shadow DOM. All it is a jQuery object that contains a div so i can append things to it. Every time a frame is elapsed the contents of the shadow DOM is copied to multiple viewports. My problem is that I can't copy the state of the canvas elements.

Is there anyway to get around this without having to update each canvas element in each viewport?

I found the best way to do this is by creating another canvas then adding the data from the old canvas directly to the new one in the following way:

//Create a blank canvas to apply the old canvas to
var newCanvas = jQuery('<canvas></canvas>'),
    newCanvasContext = newCanvas.getContext('2d');

//size the new canvas to mirror the old canvas
newCanvas[0].width = oldCanvas[0].width;
newCanvas[0].height = oldCanvas[0].height;

//copy the old canvas onto the new canvas with drawImage();
newCanvasContext.drawImage(oldCanvas[0], 0, 0, oldCanvas[0].width, oldCanvas[0].height);

I found that just copying the canvas node is not enough . The above is needed to duplicate a canvas and its data .

在SO上,您的问题有一个很好的答案: 在JavaScript中深度克隆对象的最有效方法是什么?

Found a solution. I had to copy the image data manually for each copy of the canvas. See Any way to clone HTML5 canvas element with its content? for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM