Content retention when cloning HTML5 canvas

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:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  5. <title>Sandbox</title>
  6. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  7. <script type="text/javascript">
  8. $(function() {
  9. $("#btnDraw").click(handleDraw);
  10. $("#btnClone").click(handleClone);
  11. });

  12. function handleDraw() {
  13. var context = $("#myCanvas")[0].getContext("2d");
  14. context.fillStyle = "rgb(255,0,0)";
  15. context.fillRect(30, 30, 50, 50);
  16. };

  17. function handleClone() {
  18. var clone = $("#myCanvas").clone();
  19. var target = $("#target")
  20. target.children().remove();
  21. target.append(clone);
  22. };
  23. </script>
  24. <style>
  25. canvas { border: solid 1px #aaa }
  26. </style>
  27. </head>
  28. <body>
  29. <canvas id="myCanvas" height="200" width="200">
  30. Hi. Lorem ipsum.
  31. </canvas>
  32. <br />
  33. <br />
  34. <input type="button" id="btnDraw" value="Draw" />
  35. <input type="button" id="btnClone" value="Clone" />
  36. <br />
  37. <br />
  38. <div id="target"></div>
  39. </body>
  40. </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