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.
To dynamically create HTML5 canvas with JavaScript, we can use the createElement method. const canvas = document. createElement("canvas"); canvas.id = "canvas"; canvas. width = 1224; canvas.
The HTML <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript). The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With