HTML and CSS Reference
In-Depth Information
var pattern = context.createPattern(img, "repeat");
context.fillStyle = pattern;
context.fillRect(0, 0, 200, 200);
});
img.src = "images/pattern.png";
This code creates a new instance of an Image object and sets its src property to an image that is to be
used for pattern filling. The load event handler of the Image creates a pattern using the drawing context's
createPattern() method. The first parameter of createPattern() is the image to be used, and the second
parameter indicates a repeat direction. The possible values for the repeat direction are repeat-x (repeat
horizontally), repeat-y (repeat vertically), and repeat (repeat in both the directions). The fillStyle,
property is then set to the newly created pattern object. Finally, a filled rectangle is drawn. Figure 4-21
shows how the rectangle is filled with a sample pattern.
Figure 4-21. Filling a rectangle with a pattern
Saving the Canvas State
So far, you've been playing with the canvas by performing various drawing operations on it. Many times,
you need to change the state of the canvas between drawing operations. For example, assume that you
have a canvas with settings such as lineWidth and fillStyle, set to some values. Now you wish to draw
three rectangles on the canvas. However, lineWidth and fillStyle, are different for all of them. In this case,
you set the context properties for the first rectangle and then draw the rectangle. Doing so causes the
original values to be overwritten. You repeat the same process to draw the other two rectangles. Now, if you
wish to return the canvas to the original state it was in before you began drawing the three rectangles, you
have to set those properties again because they were overwritten by the subsequent drawing operations.
Saving the canvas state allows you to restore it at some later stage.
The term state can be bit misleading. Here, the canvas state means settings such as the strokeStyle ,
fillStyle, , lineWidth , lineCap , shadowOffsetX , shadowOffsetY , shadowBlur , and shadowColor properties and
a few other settings. You may want to save a snapshot of the canvas settings at a given point of time so you
can revert back to those settings later in the current browser session. To perform these tasks, the drawing
 
Search WWH ::




Custom Search