Trusted answers to developer questions

How to draw rectangles in HTML Canvas

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

Overview

Canvas has the following APIs to draw rectangles:

  • fillRect(x, y, width, height): Draws a filled rectangle.

  • strokeRect(x, y, width, height): Draws a rectangular outline.

  • clearRect(x, y, width, height): Clears the specified rectangular area, making it fully transparent.

The xx and yy parameters specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle.

Code examples

Before we start, let’s create the 2D rendering context:

const context = canvas.getContext("2d");

Now, let’s draw a filled rectangle:

    context.fillRect(50, 0, 100, 100)

This will start the position of the rectangle from its top-left edge at the x,yx,y = (50,0)(50,0) position, and then draw the length to 100100 and width to 100100:

Let’s make the rectangle with only it’s outline:

context.strokeRect(50, 0, 100, 100)

This will draw the previous rectangle, but now only it’s outline is shown:

We can clear a section of a reactangle with clearRect. Let’s clear a mid-section of our filled rectangle:

context.fillRect(50, 0, 100, 100)
 context.clearRect(60, 10, 80, 80)

This will clear the mid-section of the filled rectangle 1010 pixels apart:

Note: Please refer to the following shots for information related to this topic:
-Drawing lines and paths
-Drawing triangles
-Filling paths
-Drawing circles and arcs

RELATED TAGS

javascript
canvas
Did you find this helpful?