Javascript new canvas

A new canvas!

In JavaScript, you can create a new canvas element using the following code:

const canvas = document.createElement('canvas');

This creates a new <canvas> element in the DOM, but it doesn't have any dimensions or content yet.

To set the dimensions of the canvas, you can use the width and height properties:

canvas.width = 400; // set the width to 400 pixels
canvas.height = 200; // set the height to 200 pixels

Alternatively, you can use the canvas constructor and pass in the dimensions as arguments:

const canvas = new Canvas(400, 200);

This will create a new canvas element with the specified dimensions.

You can also add the canvas to the DOM using the appendChild method:

document.body.appendChild(canvas);

This will add the canvas to the <body> element of the HTML document.

Once you have created and added the canvas to the DOM, you can start drawing on it using the canvas object's methods, such as getContext to get a reference to the canvas's 2D drawing context:

const ctx = canvas.getContext('2d');

And then you can use the ctx object to draw shapes, lines, and text on the canvas using methods like fillRect, strokeRect, fillText, etc.

Here is an example of creating a new canvas and drawing a simple rectangle on it:

const canvas = document.createElement('canvas');
canvas.width = 400;
canvas.height = 200;
document.body.appendChild(canvas);

const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);

This code creates a new canvas with a width of 400 pixels and a height of 200 pixels, adds it to the DOM, and then uses the getContext method to get a reference to the canvas's 2D drawing context. It then sets the fill color to red and draws a rectangle on the canvas using the fillRect method.