0

I've been looking at similar questions regarding dynamic canvas creation (1, 2), but they assuming canvas is already in the DOM. But what if I want to create and draw canvas on the fly (in other words no canvas or any other parent elements are present in the DOM)?

Something along the lines of this (which doesn't work):

<!DOCTYPE HTML>
<html>
<head>
    <title>canvas test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="js/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            for (var i = 0; i < 3; i++) {
                var canvas = $('<canvas />').attr({
                        id: "canvas" + i,
                        width: 20,
                        height: 20
                    });

                var ctx = $(canvas)[0].getContext('2d');
                ctx.fillStyle = "#000";
                ctx.fillRect(0, 0, 20, 20);
                $("#events").append("<tr><td>" + canvas[0].outerHTML + "</td></tr>");
            }
        });
    </script>
</head>
<body>
    <table id="events">
        <tr>
            <th>Canvas</th>
        </tr>
    </table>
</body>
</html>
Community
  • 1
  • 1
Martin
  • 1,460
  • 1
  • 13
  • 17

1 Answers1

1

Nothing happens because you aren't appending the canvas itself but its markup. The contents of the canvas can't be expressed in HTML so the markup is just an empty canvas tag.

So instead of appending the outerHTML, append the elements themselves.

$("<tr><td></td></tr>").appendTo( '#events' ).find( 'td' ).append( canvas );

Demo:http://jsfiddle.net/2Lr5h/

JJJ
  • 32,902
  • 20
  • 89
  • 102