Drawing Rectangles

Rectangles are the only shapes built directly into the context that can be drawn without first creating a path.

The 2D rendering context includes three methods to draw rectangles:

Method Description
fillRect(x, y, width, height) Draws a filled rectangle using the current fillStyle.
strokeRect(x, y, width, height) Draws an outlined rectangle using the current strokeStyle and lineWidth.
clearRect(x, y, width, height) Clears the specified rectangular area, making it fully transparent.

Each method takes four parameters: x and y for the top-left corner's position, and width and height for dimensions (in pixels).

Rectangle Example

This example draws a solid blue rectangle and an orange outlined rectangle on the canvas:

View Output

Coordinate System

By default, the coordinate (0,0) is at the top-left corner of the canvas. The x axis increases to the right, and the y axis increases downwards. This is different from the Cartesian coordinate system you might have learned in geometry class.

Example: Combining Rectangles

You can use these methods together to create more complex compositions. In this example, we create a filled rectangle and then use clearRect and strokeRect to add detail to it:

View Output

The next lesson will show you how to draw triangles and other custom shapes using paths.