HTML5 Guidelines for Web Developers

(coco) #1

162 Chapter 5—Canvas


In createReflection() we first use another in-memory canvas to flip the lower
half of the image section passed in icon. Thinking back to the shortcuts for trans-
formation matrices, we could achieve flipping via the matrix for flipY(). But in
this case we use another option of creating reflection, using the method scale(),
where scale(1,-1) corresponds to the method flipY() and scale(-1,1) corre-
sponds to the method flipX(). The fade-out effect is achieved via a gradient from
semitransparent white to opaque white, placed over the icon using the composit-
ing method destination-out.
Now we have defined the individual image sections and can start drawing. A
black/white gradient with almost complete black in the center of the gradient
creates the impression of 3D space, in which we then place the three images:

var grad = context.createLinearGradient(
0,0,0,canvas.height
);
grad.addColorStop(0.0,'#000');
grad.addColorStop(0.5,'#111');
grad.addColorStop(1.0,'#EEE');
context.fillStyle = grad;
context.fillRect(0,0,canvas.width,canvas.height);

The center picture of Merced River is the easiest to position via setTransform();
we can then draw it with a reflection effect:

context.setTransform(1,0,0,1,440,160);
context.drawImage(icons[1],0,0,320,320);
context.drawImage(effects[1],0,320,320,160);

The width of the El Capitan image on the right is scaled by 0.9 to achieve a better
3D effect. The result is skewed by 10° downward via the matrix for skewY() and
positioned to the right of the center:

context.setTransform(1,0,0,1,820,160);
context.transform(1,Math.tan(0.175),0,1,0,0);
context.scale(0.9,1);
context.drawImage(icons[2],0,0,320,320);
context.drawImage(effects[2],0,320,320,160);

Drawing the Taft Point image on the left is a bit more complicated. After skewing,
the top-left corner of our section forms the anchor point; we then have to skew
upward by 10° and then move the result downward again. Pythagoras’ theorem
will help us determine the required dy value: It results as tangent of the rotation
angle in radians multiplied by the length of the cathetus corresponding to the
width of the icon, so Math.tan(0.175)*320. We also have to compensate for scal-
ing the image width by 0.9 by shifting it to the right by 320*0.1:
Free download pdf