5.2 Rectangles 111
5.2 Rectangles
Canvas has four methods for creating rectangles. Three of these we will discuss
now, the fourth we will encounter later in connection to paths:
context.fillRect(x, y, w, h)
context.strokeRect(x, y, w, h)
context.clearRect(x, y, w, h)
The names of these methods are self-explanatory: fillRect()creates a filled
rectangle, strokeRect() a rectangle with border and no filling, and clearRect() a
rectangle that clears existing content like an eraser. The rectangle’s dimensions
are determined by four numerical parameters: origin x/y, width w, and height h.
In Canvas, the coordinate origin is at the top left, which means the x coordi-
nates increase toward the right and the y coordinates toward the bottom (see
Figure 5.3).
Figure 5.3 The Canvas coordinate system
In parallel to the first example, we first define a reference to the canvas element
in our bar chart and then the drawing context. The function drawBars()is re-
sponsible for doing the main job, drawing the horizontal bars. We pass the de-
sired number of bars we want to draw to this function: