1

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?

Robert Hurst
  • 8,902
  • 5
  • 42
  • 66

3 Answers3

2

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.

Robert Hurst
  • 8,902
  • 5
  • 42
  • 66
1

There's an excellent answer to your question right here on SO: What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
musicinmyhead
  • 1,466
  • 9
  • 11
0

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.

Community
  • 1
  • 1
Robert Hurst
  • 8,902
  • 5
  • 42
  • 66