18

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.

2 Answers 2

26

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.)

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

Comments

14

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);

2 Comments

@Ben, @Matt -- Both solutions work. Voted for both of them already. Thanks a lot!
@pion: you're welcome. I just noticed that our answers were posted within 1 second of each other...

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.