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>

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.