HTML5 Guidelines for Web Developers

(coco) #1
5.10 Patterns 153

Figure 5.33 Checkered pattern in eight color combinations


The pattern is created as an in-memory canvas with a 20 × 20 pixel width and four
10 × 10 pixel squares. Illustrated using the example of the green pattern, this step
looks as follows:


var cvs = document.createElement("CANVAS");
cvs.width = 20;
cvs.height = 20;
var ctx = cvs.getContext('2d');
ctx.fillStyle = 'lime';
ctx.fillRect(0,0,10,10);
ctx.fillRect(10,10,10,10);
ctx.fillStyle = 'green';
ctx.fillRect(10,0,10,10);
ctx.fillRect(0,10,10,10);


We then define the canvas cvs as a repeating pattern using createPattern(), as-
sign it to the attribute fillStyle, and use it to fill the square:


context.fillStyle = context.createPattern(cvs,'repeat');
context.fillRect(0,0,220,220);

Free download pdf