Related Tags

javascript
canvas
communitycreator

# How to draw rectangles in HTML Canvas

Chidume Nnamdi

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

### 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 $x$ and $y$ 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,y$ = $(50,0)$ position, and then draw the length to $100$ and width to $100$:

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 $10$ 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
communitycreator

CONTRIBUTOR

Chidume Nnamdi