Web APIs help you develop your websites, and Canvas API is one of them. It uses the HTML element
Behind the scenes, a canvas is a single DOM element that encapsulates any graphics. So, the Canvas API gives an interface to draw shapes taken up by this DOM element programmatically. The Canvas uses a "Render and Forget" mechanism. Anything we draw is rendered immediately, and once it is rendered, the Canvas only knows the shapes as pixels, not objects.
Canvas API enjoys healthy support from the browsers and is widely used for simple and complex animations, data visualization, games, photo manipulation, and video processing.
<canvas> element takes two attributes,
useRef hook to access it.
The first thing we need is the canvas element. This is how we create it in HTML:
<canvas id=”cnv” width=”60" height=”60"></canvas>
const canvas = document.getElementById('cnv');const ctx = canvas.getContext('2d');
ctx has been initialized as a context object, we can call the methods provided by the canvas API.
fillStyle method specifies the color of the shapes you draw on the canvas. For example, this code will color the shapes blue.
ctx.fillStyle = 'blue';
fillRect method draws a rectangle on the specified coordinates.
ctx.fillRect(10, 10, 150, 100);
Here the first two parameters,
10, 10 are x and y coordinates of the starting point,
150 is the width and
100 is the height.
Click on the submit button below to see what it looks like:
Paths allow you to draw any shape using a list of points. These points are connected by lines that can have different shapes, curves, and styles. There are three steps required to draw paths on a canvas:
Check out the code below. Can you guess what shape it will draw? Try submitting it to see the canvas output.
This guide was an introduction to the basic concepts of the Canvas API. I hope it has made it easier for you to get started with the Canvas API and dive deeper into it.