JavaScript Answers

How to Create an HTML Canvas with JavaScript?

Spread the love

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *