Chapter 6: Advanced Programming Topics: Canvas and Video
140
Creating an Image Pattern
You can use an external image to create an image pattern on the back of a canvas element using the
createPattern()
method. The syntax is:
patternObject = context.createPattern(image, type)
The
image
argument references an
Image
object or else a different
canvas
element. The
type
argument
is one of the familiar CSS pattern types:
repeat
,
repeat-x
,
repeat-y
, and
no-repeat
. The method
returns a
Pattern
object, as shown in the following example:
function drawPattern(){
var canvas = document.getElementById(‘myCanvas’);
❑
shadowColor
defines the CSS color of the shadow.
❑
shadowBlur
specifies the width of the shadow blur.
❑
shadowOffsetX
defines the horizontal offset of the shadow.
❑
shadowOffsetY
specifies the vertical offset of the shadow.
The following code uses these properties to define a blurred shadow for an image:
function drawImg(){
var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);
c06.indd 140c06.indd 140 12/7/07 2:48:25 PM12/7/07 2:48:25 PM
Chapter 6: Advanced Programming Topics: Canvas and Video
141
context.shadowColor = “black”;
context.shadowBlur = “10”;
context.shadowOffsetX = “5”;
context.shadowOffsetY = “5”;
var img3 = new Image();
img3.src = ‘images/nola.jpg’;
img3.onload = function() {
as it draws a circle successive times onto the
canvas. Each time these methods are called, their parameters are adjusted:
c06.indd 142c06.indd 142 12/7/07 2:48:25 PM12/7/07 2:48:25 PM
Chapter 6: Advanced Programming Topics: Canvas and Video
143
function transform(){
var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);
var s=1;
for (i=1;i<6;i++){
var t=i*8;
context.translate(t,t);
context.scale(s,s);
context.fillStyle = “rgba(“ + t*4 + “,”+ t*6 + “,” + t*8 + “, 0.3)”;
context.beginPath();
context.arc(50,50,40,0,2*pi , false);
context.fill();
s=s-0.05;
}
}
The
t
variable is
8
times the current iteration of the
for
loop, and then is used as the parameters for
translate()
. The
var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);
context.globalAlpha=”0.5”;
var r=1;
var img = new Image();
img.src = ‘images/jared.jpg’;
img.onload = function() {
for (i=1;i<4;i++) {
context.translate(50,-15);
context.rotate(.15*r);
context.globalAlpha=i*.33;
context.drawImage(img, 20, 20);
r+=1;
}
}
}
Figure 6-14 shows the layered result. Note the difference in transparency of the bottommost image to
the topmost.
Saving and Restoring State
When you begin to work with more advanced drawings on the canvas, you will need to manage the
drawing state. A drawing state includes the current path, the values of the major context properties (such
as
fillStyle
and
globalAlpha
), and any transformations (such as rotating) that have been applied.
To this end, you can use the
save()
and
restore()