To create an HTML canvas with JavaScript, we can use the document.createElement
method.
For instance, we can write:
const canvas = document.createElement('canvas');
canvas.width = 100;
canvas.height = 100;
document.body.appendChild(canvas)
const ctx = canvas.getContext("2d");
We call document.createElement
with 'canvas'
to create a canvas element.
Then we set its width and height by setting the width
and height
properties.
Next, we call document.body.appendChild
with canvas
to attach it to the body element as its child.
Finally, we call canvas.getContext
to get the 2d context.