HTML5 Canvas [14]
The Basic File Setup for This Chapter
As we proceed through the Drawing API, all the examples in this chapter will use the same basic file setup, shown below. Use this code as the basis for all of the examples we create. You will only have to change the contents of the drawScreen() function:
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 very 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.fillRect(10,10,40,40);
context.strokeRect(0, 0,60,60);
context.clearRect(20,20,20,20);
}
Figure 2-1. Basic rectangles
The Canvas State
When we draw on the Canvas context, we can make use of a stack of so-called drawing states. Each of these states stores data about the Canvas context at any one time. Here is a list of the data stored in the stack for each state:
Transformation matrix information such as rotations or translations using the context.rotate() and context.setTransform() methods
The current clipping region
The current values for canvas attributes, such as (but not limited to):
globalAlpha
globalCompositeOperation
strokeStyle
textAlign, textBaseline
lineCap, lineJoin, lineWidth, miterLimit
fillStyle
font
shadowBlur, shadowColor, shadowOffsetX, and shadowOffsetY
We will cover these states later in this chapter.
What’s Not Part of the State?
The current path (which we will explore later in this chapter) and current bitmap (see Chapter