Content retention when cloning HTML5 canvas
Hi,
I am trying to clone an HTML5 canvas element with content drawn dynamically on it. However, when I use .clone() on the element, the contents are not copied.
I tried attaching an example .html file to illustrate the problem, but the forum does not allow me to. Instead, I'm pasting the code below:
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
- <title>Sandbox</title>
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
- <script type="text/javascript">
- $(function() {
- $("#btnDraw").click(handleDraw);
- $("#btnClone").click(handleClone);
- });
- function handleDraw() {
- var context = $("#myCanvas")[0].getContext("2d");
- context.fillStyle = "rgb(255,0,0)";
- context.fillRect(30, 30, 50, 50);
- };
- function handleClone() {
- var clone = $("#myCanvas").clone();
- var target = $("#target")
- target.children().remove();
- target.append(clone);
- };
- </script>
- <style>
- canvas { border: solid 1px #aaa }
- </style>
- </head>
- <body>
- <canvas id="myCanvas" height="200" width="200">
- Hi. Lorem ipsum.
- </canvas>
- <br />
- <br />
- <input type="button" id="btnDraw" value="Draw" />
- <input type="button" id="btnClone" value="Clone" />
- <br />
- <br />
- <div id="target"></div>
- </body>
- </html>
If you click on the "Draw" button and then "Clone", you'll see that the canvas element is copied, but the contents are dropped.
Any help would be greatly appreciated.
Thanks,
Elliot