CodeBlanks Logo Icon CodeBlanks

Drawing rectangles

JavaScript course · Expert · Lesson 44/63

Learn to draw rectangles with fillRect, strokeRect and clearRect.

Filled rectangles with fillRect

fillRect(x, y, width, height) draws a filled rectangle. The first two numbers are the top-left corner, the last two are the size.

The fill color is set by the fillStyle property. The color is written as a string, for example 'red' or '#00ff00'. The color must be set before the fillRect call, because drawing uses the current color.

strokeRect and clearRect

strokeRect draws only the outline of the rectangle; it leaves the inside empty. You set the outline color with strokeStyle.

clearRect erases a rectangular region and makes it transparent. It is often used in animation to clear the previous frame. All three methods take the same four arguments: x, y, width, height.

Exercise Filled and stroked rectangle

First set the fill color to red with ctx.fillStyle = 'red' and draw a filled rectangle with ctx.fillRect(10, 10, 60, 40). Then set the stroke color to blue with ctx.strokeStyle = 'blue' and draw the stroked rectangle with ctx.strokeRect(10, 10, 60, 40).

Show example solution
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 60, 40);
ctx.strokeStyle = 'blue';
ctx.strokeRect(10, 10, 60, 40);

Test yourself

  1. When should fillStyle be set?

    ctx.fillStyle = 'red';
    ctx.fillRect(10, 10, 50, 30);
    • Before the fillRect call
    • After the fillRect call
    • On the same line as fillRect
    • Set automatically after drawing
    Show answer

    Before the fillRect call — Correct! fillStyle must be set before fillRect; drawing uses the current color.

  2. Draw a filled rectangle

    ctx.____(10, 10, 50, 30);
    Show answer
    ctx.fillRect(10, 10, 50, 30);
  3. Match the rectangle methods

    fillRect
    filled rectangle
    strokeRect
    outline
    clearRect
    clear
    fillStyle
    fill color

All lessons in Expert