Figure 6-12: Shadow effects
Transforming a Canvas State
The context object has three methods you can use for transforming the state of a canvas:
??‘ translate(x, y) changes the origin coordinate (0,0) of the canvas.
??‘ rotate(angle) rotates the canvas around the current origin of a specified number of radians.
??‘ scale(x, y) adjusts the scale of the canvas. The x parameter is a positive number that scales
horizontally, while the y parameter scales vertically.
The following example uses translate() and scale() as it draws a circle successive times onto the
canvas. Each time these methods are called, their parameters are adjusted:
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 scale() method uses the s variable, which is decremented by 0.
Pages:
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172