Introduction to Canvas

Get familiarized with HTML canvas and draw a few graphics on the web page using JavaScript.

What is an HTML canvas element?

The HTML <canvas> element is used to draw graphics on a web page using JavaScript. In HTML, the canvas looks just like a container that can hold and display our graphics to the user on the web page. To draw the graphics inside the canvas container, we need to use JavaScript. We can create different types of shapes, colors, images, and so on.

Draw a rectangle using canvas

Let's see an example of an HTML canvas element where we create a rectangle inside the canvas container. We'll perform the following steps:

  1. Access the canvas element from the HTML.

  2. Set the properties of the canvas element.

  3. To draw the graphics on the canvas, we need a context object. The canvas context object provides a set of properties and methods to draw the graphics on a canvas element. To get this, we will use getContext() method and pass a parameter as 2d because we are drawing 2D graphics.

  4. To draw a rectangle, we will be using the fillRect() method, which accepts four parameters:

  • The x and y coordinate of the start position of the rectangle.

  • The width of the rectangle.

  • The height of the rectangle.

Now let's see how to implement this in the code below:

Get hands-on with 1200+ tech skills courses.