HTML5 Guidelines for Web Developers

(coco) #1

158 Chapter 5—Canvas


Listing 5.2 shows the very short source code in Figure 5.36.

Listing 5.2 Source code of the transformations shown in Figure 5.36
image.onload = function() {
var rotate = 15;
var scaleStart = 0.0;
var scaleEnd = 4.0;
var scaleInc = (scaleEnd-scaleStart)/(360/rotate);
var s = scaleStart;
for (var i=0; i<=360; i+=rotate) {
s += scaleInc;
context.translate(540,260);
context.scale(s,s);
context.rotate(i*-1*Math.PI/180);
context.drawImage(image,0,0,120,80);
context.setTransform(1,0,0,1,0,0);
}
};

As soon as the image is loaded, we define the angle of rotation rotate as 15°, the
start and end scaling scaleStart as 0.0 and scaleEnd as 4.0, and derived from this
the increment for scaling scaleInc with the aim of achieving the end scale 4.0
within a full rotation. In the for loop we then rotate the image counterclockwise
by 15° each time, scale it from 0.0 to 4.0, and set its top-left corner to the coordi-
nate 540/260.
So why do we have the method setTransform() at the end of the for loop?
Apart from the basic transformations scale(), rotate(), and translate(), Can-
vas offers two other methods for changing the coordinate system and therefore
the transformation matrix: transform() and setTransform(), which were already
mentioned in Listing 5.2:

context.transform(m11, m12, m21, m22, dx, dy);
context.setTransform(m11, m12, m21, m22, dx, dy);

Both have the arguments m11, m12, m21, m22, dx, and dy in common, representing
the transformation properties listed in Table 5.3.
Free download pdf