Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create HTML5 Canvas programmatically

Tags:

html

canvas

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.

like image 671
pion Avatar asked Jan 22 '11 03:01

pion


People also ask

How do I create a dynamic canvas?

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.

How does HTML5 work on 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.


2 Answers

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

like image 190
Sophie Alpert Avatar answered Sep 22 '22 15:09

Sophie Alpert


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);
like image 39
Matt Ball Avatar answered Sep 18 '22 15:09

Matt Ball