HTML and CSS Reference
In-Depth Information
Fill patterns are initialized with the createPattern() function, which takes two param-
eters. The first is an Image object instance, and the second is a String representing how
to display the repeat pattern inside the shape. We can use a loaded image file or an
entire other canvas as a fill pattern for a drawn shape.
There are currently four types of image fills:
Modern browsers have implemented these four types to various degrees, but standard
repeat seems to be the most common. Let's look at it now and then we will take a brief
look at the other three.
Figure 2-34 shows a simple bitmap fill pattern that we can use to test this functionality.
It is a 20×20 green circle on a transparent background, saved as a .gif file named
fill_20x20.gif .
Figure 2-34. The fill_20x20.gif image for our fill
Example 2-25 tests this first with the repeat string to create a box full of little green
circles, as shown in Figure 2-35 .
Example 2-25. Filling with an image file using repeat
function drawScreen() {
var fillImg = new Image();
fillImg.src = 'fill_20x20.gif';
fillImg.onload = function(){
var fillPattern = context.createPattern(fillImg,'repeat');
context.fillStyle = fillPattern;
It is best not to use Image instances until they have loaded completely. We will cover
this in detail in Chapter 4 , but for now, we simply create an inline onload event handler
function that will be called when Image is ready to be used. The repeat pattern string
does a good job of completely filling the 200×200 square. Let's see the code for how
the other repeat strings perform (in Example 2-26 ), and view the results in Figures
2-36 through 2-38 .
Search WWH ::

Custom Search