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.

The fill_20x20.gif image for our fill

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;
         context ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.