40
tileSheet.addEventListener('load', eventSheetLoaded , false);
tileSheet.src = "mediumrocks.png";
The rotationImageArray variable holds the generated imageData instances, which we
create by using a rotation transformation on theCanvas2.
The animationFrame is used when redisplaying the rotation animation frames in rota
tionImageArray back to the first theCanvas to demo the animation.
When the tileSheet is loaded, the eventSheetLoaded() function is called, which in
turn calls the startup() function. The startup() function uses a loop to create the 36
frames of animation:
function startUp(){
for (var ctr=0;ctr<360;ctr+=10){
context2.fillStyle = "#ffffff";
context2.fillRect(0,0,32,32);
context2.save();
context2.setTransform(1,0,0,1,0,0)
var angleInRadians = ctr * Math.PI / 180;
context2.translate(16, 16);
context2.rotate(angleInRadians);
context2.drawImage(tileSheet, 0, 0,32,32,-16,-16,32,32);
context2.restore();
var imagedata = context2.getImageData(0, 0, 32, 32)
rotationImageArray.push(imagedata);
}
setInterval(drawScreen, 100 );
}
This loop first clears theCanvas2 with a white color and then saves it to the stack. We
then translate to the center of our object and rotate the canvas by the current ctr value
(an increment of 10). Next, we draw the first tile from mediumrocks.png and save the
result in a new local imageData instance, using the getImageData() function.
This is where the security error will be thrown if the domain of the
image and the domain of the HTML file are not the same. On a local
machine (not running on a local web server, but from the filesystem),
this error will be thrown on all browsers but Safari (currently).
Finally, the new imageData is pushed into the rotationImageArray. When the loop is
complete, we set up an interval to run and call the drawScreen() function every 100
milliseconds.
To display the animation on the first canvas, we use this timer loop interval and call
putImageData() to draw each frame in succession, creating the simulation of animation.
As with the tile sheet, we didn’t have to use 36 frames of animation; we could use just
552 | Chapter 9: Canvas Games: Part II