pion
pion

Reputation: 3613

Create HTML5 Canvas programmatically

I have the following HTML code snippets

<body onload="main()" >
    ...
    <canvas id="myId" class="myClass"></canvas>
    ...
</body>

It works as expected. I can display the output correctly.

I then remove

<canvas id="myId" class="myClass"></canvas>

Because I want to create it programmatically with the following JavaScript code snippet

var canvas = document.createElement("canvas");
canvas.className  = "myClass";
canvas.id = "myId";

Unfortunately, it didn't work. I cannot display anything with this.

I am wondering if I miss something. Any help is appreciated. Thanks in advance for your help.

Upvotes: 18

Views: 22341

Answers (2)

Matt Ball
Matt Ball

Reputation: 359816

You need to actually attach the canvas to the document. Before you do so, it's just a detached element that the browser does not render.

var canvas = /* ... */;
/* ... */
document.getElementsByTagName('body')[0].appendChild(canvas);

Upvotes: 14

Sophie Alpert
Sophie Alpert

Reputation: 143134

You need to insert the new <canvas> element into the DOM. To put it at the end of the body, use:

document.body.appendChild(canvas);

with the code that creates it. (If you want to put it inside a different element, use that instead of document.body.)

Upvotes: 26

Related Questions