Drawing Rectangles
Explore how to draw rectangles and squares on the HTML5 canvas using JavaScript methods like rect, fillRect, and strokeRect. Understand defining paths, outlining shapes, and filling colors to create solid and outlined 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:
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