Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Drawing by using the element CHAPTER 12 469


Figure 12-4 shows a small image with a rectangle and a circle. This image has a trans-
parent background, and there is no border around the edge of the image.

FIGURE 12-4 mage used to create a repeating patternI

By using the image in Figure 12-4, the following code creates a pattern that is assigned
to the fillStyle property.
function drawPattern() {
var canvas = document.getElementById('myCanvas')
, ctx = canvas.getContext('2d');

// create new image object to use as pattern
var img = new Image();
img.src = 'images/pattern.gif';
img.onload = function () {
// create pattern
var ptrn = ctx.createPattern(img, 'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0, 0, 400, 400);
}
}

In this example, instead of creating an <img> element, the image is dynamically created,
and its source (src) is set to the pattern.gif file. Next, the onload event of the image is sub-
scribed to that creates the pattern on the canvas after the pattern.gif file is loaded. The result
is shown in Figure 12-5.
Free download pdf