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 开发者_StackOverflow中文版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.
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
.)
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);
精彩评论