canvas in javascript

In JavaScript, the canvas is an HTML5 element that provides a space on which you can draw graphics using JavaScript. The canvas element is essentially a rectangular region that is controlled through scripting and rendered in real-time.

Here's an example of how to create a canvas element in HTML:

<canvas id="myCanvas"></canvas>
32 chars
2 lines

And here's how to access the canvas element in JavaScript:

index.tsx
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
85 chars
3 lines

Once you have access to the canvas context, it's time to start drawing. The getContext function returns a 2D drawing context on which we can draw shapes, lines, text and images. Here is an example of how to draw a rectangle:

index.tsx
ctx.fillStyle = "red";        // Set the fill color to red
ctx.fillRect(10, 10, 50, 50); // Draw a red, 50x50 rectangle at 10, 10
130 chars
3 lines

This code will result in a red rectangle being drawn on the canvas element at position (10, 10), with a width of 50 pixels and a height of 50 pixels.

There are many other functions and properties available in the canvas context, allowing you to draw a wide range of shapes and styles.

gistlibby LogSnag