Learning the Canvas: Part 2
This is part of an ongoing series of posts about learning how to use the HTML canvas element. If you haven’t already seen part 1, I recommend you check out Learning the Canvas: Part 1.
Last time we only used one function to draw rectangles: fillRect()
. But in fact, there are two other functions that can be used to draw rectanges as well: strokeRect()
and clearRect()
. All three methods take the same parameters: x
, y
, width
, and height
. For the x and y position, remember that the “starting” coordinates are the top-left corner of the rectangle.
Combining these three functions to form a single drawing can produce some pretty interesting results.
When you look at the above image, what do you see?
Some see a bird’s eye view of a tall pryamid, while others see a first-person view down long hallway.
The code for this example is a combination of the three methods mentioned above.
You can see how these functions give us more flexibility on what we can draw, and how we can draw it.
We can leverage loop structures to draw on bigger canvases without much additional code.
Building upon that example, we can imagine all sorts of rectangular-based drawings using a combination of these three functions.
Even though it appears as a board with many squares, in the code we see it’s actually long rectangles rendered on top of each other to achieve the appearance of squares.
This is only the beginning of what you can do with the HTML canvas. In the next post, we’ll cover paths, which are an extremely powerful set of tools for drawing almost any shape you can think of.