Cool effect with the canvas element

var cdCase;
var stitch;
var reflections;
var cover;

function loadImages() {
var loader = new ImagePreloader([“http://jext.free.fr/canvas-test/cd_case.png”, “http://jext.free.fr/canvas-test/stitch.png”, “http://jext.free.fr/canvas-test/reflections.png”, “http://jext.free.fr/canvas-test/Shivaree.jpg”],
onPreload);
}

function onPreload(loadedImages) {
cdCase = loadedImages[0];
stitch = loadedImages[1];
reflections = loadedImages[2];
cover = loadedImages[3];

drawCD();
}

function drawCD() {
var g2 = document.getElementById(“cdCover”).getContext(“2d”);

g2.save();
g2.translate(0, cdCase.height * 2 – 1);
g2.scale(1, -1);

g2.beginPath();
g2.moveTo(0, cdCase.height / 2);
g2.lineTo(cdCase.width, cdCase.height / 2);
g2.lineTo(cdCase.width, cdCase.height + 1);
g2.lineTo(0, cdCase.height + 1);
g2.clip();

g2.drawImage(cover, 19, 3, 240, 227);
g2.drawImage(reflections, 0, 0);
g2.drawImage(stitch, 19, 3);
g2.drawImage(cdCase, 0, 0);

g2.globalCompositeOperation = “destination-out”;
var alphaMask = g2.createLinearGradient(0, cdCase.height / 2, 0, cdCase.height);
alphaMask.addColorStop(0, “rgba(255, 255, 255, 1.0)”);
alphaMask.addColorStop(1.0, “rgba(255, 255, 255, 0.5)”);
g2.fillStyle = alphaMask;
g2.fillRect(0, cdCase.height / 2, cdCase.width, cdCase.height / 2);

g2.restore();

g2.drawImage(cover, 19, 3, 240, 227);
g2.drawImage(reflections, 0, 0);
g2.drawImage(stitch, 19, 3);
g2.drawImage(cdCase, 0, 0);
}

Safari and Opera had it for a while but Firefox is catching up. The new canvas tag let you draw very cool things in a browser with a bit of JavaScript code. I ported my old Crystal CD Case effect to JavaScript. You can check it out here: http://jext.free.fr/canvas-test/canvas-test.html.

There are some trouble starting the drawing operations when all pictures are loaded so if you see nothing (you need Firefox 1.5 or one of the aforementionned browsers), try to reload the page a few times.

The API will look familiar to any Java2D programmer. That is really cool and I bet we will soon see very cool things on the web (hopefully more useful than the impressive FPS demo Slashdot ran a story about).

If everything is fine you should see my stuff below:

loadImages();

Comments are closed.