HTML5 Guidelines for Web Developers

(coco) #1

154 Chapter 5—Canvas


Patterns are anchored to the coordinate origin and applied starting from that
point. If we were to begin fillRect() in the preceding example ten pixels to the
right, at 10/0 instead of at 0/0, the first color in the top-left corner would be green
instead of lime.
In addition to user-defined canvas elements, we can also use images as sources
of patterns. Figure 5.34 shows an example using createPattern() to fill the back-
ground, to create a pattern for the title text, and to cut out individual sections
of the familiar Yosemite picture. The two other pictures, pattern_107.png and
pattern_125.png, are part of the Squidfingers pattern library, where you have
the choice of nearly 160 other appealing patterns to download: http://www.
squidfingers.com/patterns.

Figure 5.34 Pattern using images as a source

Let’s first look at how the background is created:

var bg = new Image();
bg.src = 'icons/pattern_125.png';
bg.onload = function() {
context.globalAlpha = 0.5;
context.fillStyle = context.createPattern(bg,'repeat');
context.fillRect(0,0,canvas.width,canvas.height);
};
Free download pdf