Another cool & easy proggie - fade in an image using random boxes!
Here's how it works (source code below):
[Lines 1-4] Set up HTML5 Canvas
[5-6] the source image
[7-8] get the 2d context of the Canvas
[9] the dimensions of the box
[10] the number of rows and columns of the random boxes
[12] once the image is loaded:
[13-14] calculate the width and height of the boxes
[15] start the animation!
[18-23] the main animation function:
[19-20] select a random box
[21] This is the heart and soul of this solution:
We are copying a bitmap box, whose dimensions are boxWidth x boxHeight at the coordinates (x * boxWidth, y * boxHeight) from the image to the Canvas. Click here to read more details about the drawImage function.
context.drawImage(image, x * boxWidth, y * boxHeight, boxWidth, boxHeight, x * boxWidth, y * boxHeight, boxWidth, boxHeight);
requestAnimationFrame(animate);
}
</script>
</body>
</html>
This keeps running forever and the code just keeps copying the boxes which were already copied.
Here's a more interesting version, that toggles between two images.
To achieve that, we need to introduce a counter [13] which will be increased after each animation frame [26].
[27-28] If the counter reaches 500, display the entire image. This is needed to avoid a situation where we have two or three boxes left to be drawn, but the computer keeps randomly selecting other boxes.
[30-35] After a 100 more frames, we switch the source image and reset the counter.