I am using javascript to draw to a canvas element inside a div, contained within a wrapper.
The canvas and its div are generated dynamically by adding to the wrapper’s innerHTML.
The goal is to allow an infinite number of canvases to be generated
<div id="wrapper">
<div id="container"><canvas id="previous"></canvas></div>
<!-- infinite # of container divs & canvases -->
</div>
However, when I add a new div and canvas to the wrapper’s innerHTML anything drawn to the previous canvas is lost.
Where if I add a new canvas elsewhere on the page, to a div outside of the container, or a child of the container:
<div id="wrapper">
<div id="container"><canvas id="previous"></canvas></div>
</div>
<div id="wrapper2">
<!-- newly inserted canvas: -->
<div id="container"><canvas></canvas></div>
</div>
or:
<div id="wrapper">
<div id="container"><canvas id="previous"></canvas></div>
<div id="wrapperChild">
<!-- newly inserted canvas: -->
<div id="container"><canvas></canvas></div>
</div>
</div>
Then the previous canvas is preserved.
From what I can tell changing the innerHTML of the wrapper or it’s parents results in clearing the canvas. Any advice on how I can avoid clearing the canvas? Can I preserve what’s been drawn to the canvas elsewhere and restore it?
Regardless of your javascript approach (jQuery, something else, or nothing), you can do this by not using innerHTML. Basically, when you append to the innerHTML property, you’re saying “take the value of innerHTML, add it to this new value (the canvas element, perhaps), then set innerHTML to all of that. In other words, you aren’t really appending “in place”. You’re basically adding a fresh version of everything you have, and since the canvas isn’t drawing its contents with child elements, they aren’t going to be brought over with this method.
Instead of using innerHTML, you should be working with the DOM, appending children to the parent as nodes instead of strings.