Drawing Rectangles

We'll cover the following...

To help explain how to work with rectangles, let’s work together on a simple example. First, make sure you have a canvas element defined in your HTML page, and give it an id of myCanvas. To help you out with this, here is what my HTML looks like:

Press + to interact
<!DOCTYPE html>
<html>
<head>
<title>Rectangle Canvas Example</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
</script>
</body>
</html>

There isn’t much going on here…except for the totally sweet canvas element whose id value is myCanvas with a width and height of 500 pixels.

Meet the rect Method

It is inside this canvas element we will draw our rectangles, and the primary way you draw a rectangle is by using the rect method to define a rectangular path. This method takes four arguments that map to the following things:

  • Starting x position the rectangle will start from
  • Starting y position the rectangle will start from
  • Width of the rectangle
  • Height of the rectangle
...