5.11 Transformations 161
var clipIcon = function(img,x,y,width,height) {
var cvs = document.createElement("CANVAS");
var ctx = cvs.getContext('2d');
cvs.width = 320;
cvs.height = 320;
ctx.drawImage(img,x,y,width,height,0,0,320,320);
ctx.strokeStyle = '#FFF';
ctx.lineWidth = 15;
ctx.strokeRect(0,0,320,320);
return cvs;
};
In a second step, we create the reflection effect for each of these three image sec-
tions and save it in the array effects:
var effects = [];
for (var i=0; i<icons.length; i++) {
effects[i] = createReflection(icons[i]);
}
The main work is done in the function createReflection(), the slightly modi-
fied code of which has been taken from a blog post in Charles Ying’s blog about
art, music, and the art of technology about the iPhone’s CoverFlow effect (see the
shortened web link http://bit.ly/b5AFW6)::)
var createReflection = function(icon) {
var cvs = document.createElement("CANVAS");
var ctx = cvs.getContext('2d');
cvs.width = icon.width;
cvs.height = icon.height/2.0;
// flip
ctx.translate(0,icon.height);
ctx.scale(1,-1);
ctx.drawImage(icon,0,0);
// fade
ctx.setTransform(1,0,0,1,0,0);
ctx.globalCompositeOperation = "destination-out";
var grad = ctx.createLinearGradient(
0,0,0,icon.height/2.0
);
grad.addColorStop(0,'rgba(255,255,255,0.5)');
grad.addColorStop(1,'rgba(255,255,255,1.0)');
ctx.fillStyle = grad;
ctx.fillRect(0,0,icon.width,icon.height/2.0);
return cvs;
};