HTML and CSS Reference
In-Depth Information
Filling Shapes with Patterns
We will cover using bitmap images on the canvas in
Chapter 4
, but for now, let's take a quick
look at how images can be used as fill patterns for shapes we draw.
Fill patterns are initialized with the
createPattern()
function, which takes two parameters.
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:
1.
repeat
2.
repeat-x
3.
repeat-y
4.
no-repeat
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
as shown in
Figure 2-35
.
Example 2-25. Filling with an image file using repeat
function
function
drawScreen
() {
var
var
fillImg
=
new
new
Image
();
fillImg
.
src
=
'fill_20x20.gif'
;
fillImg
.
onload
=
function
function
(){
var
var
fillPattern
=
context
.
createPattern
(
fillImg
,
'repeat'
);
context
.
fillStyle
=
fillPattern
;
context
.
fillRect
(
0
,
0
,
200
,
200
);