The Basic Rectangle Shape

Let’s get our feet wet by looking at the single primitive, built-in geometric shape on Canvas—the rectangle. On Canvas, basic rectangle shapes can be drawn in three different ways: filling, stroking, or clearing. We can also build rectangles (or any other shape) by using paths, which we will cover in the next section.

First, let’s look at the API functions used for these three operations:

fillRect(x,y,width,height)

Draws a filled rectangle at position x,y for width and height.

strokeRect(x,y,width,height)

Draws a rectangular outline at position x,y for width and height. This makes use of the current strokeStyle, lineWidth, lineJoin, and miterLimit settings.

clearRect(x,y,width,height)

Clears the specified area and makes it fully transparent (using transparent black as the color) starting at position x,y for width and height.

Before we can use any of these functions, we will need to set up the fill or stroke style that will be used when drawing to the canvas.

The most basic way to set these styles is to use a color value represented by a 24-bit hex string. Here is an example from our first demonstration:

context.fillStyle = '#000000';
context.strokeStyle = '#ff00ff';

In Example 2-1, the fill style is simply set to be the RGB color black, while the stroke style is a classic purple color. The results are shown in Figure 2-1.

Example 2-1. Basic rectangles

function drawScreen() {
      context.fillStyle  = '#000000';
      context.strokeStyle = '#ff00ff';
      context.lineWidth  = 2;
      context ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.