HTML5 Guidelines for Web Developers

(coco) #1
5.10 Patterns 155

The first two lines create a new Image object, setting its src attribute to the image
pattern_125.png in the folder icons. Just as with drawImage(), we need to make
sure that the image is really loaded before defining the pattern. The function
bg.onload() contains the real code for generating the repeating pattern, which
we apply at 50% opacity to the whole canvas area. With the same procedure, we
fill the title text Yosemite! with the image pattern_107.png.


For the overlapping image sections, we simply enter the whole Yosemite photo
yosemite.jpg as the pattern and then work in a for loop through the input array
extents, which contains the x-, y-, width-, and height-values of the sections we
want. By calling fillRect(), the relevant image area is shown as fill pattern and
receives an additional border with strokeRect():


var extents = [
{ x:20,y:50,width:120,height:550 } // and 7 others ...
];
var image = new Image();
image.src = 'images/yosemite.jpg';
image.onload = function() {
context.fillStyle = context.createPattern(
image,'no-repeat'
);
for (var i=0; i<extents.length; i++) {
var d = extents[i]; // short-cut
context.fillRect(d.x,d.y,d.width,d.height);
context.strokeRect(d.x,d.y,d.width,d.height);
}
};


Three different images are used in Figure 5.34, and all three must be fully loaded
before they can be used, so we need to nest the three onload functions. This en-
sures that we can control the correct order during drawing. The pseudo-code for
a possible nesting looks like this:


// create all images
bg.onload = function() {
// draw background
image.onload = function() {
// add image cutouts
pat.onload = function() {
// fill title with pattern
};
};
};


The only option to avoid this kind of nesting would be to link all involved images
in the page’s HTML code as hidden img elements via visibility:hidden and to
reference them with getElementById() or getElementsByTagName() after loading
the page in window.onload().

Free download pdf