creature rollover animation from sprite sheet
by jmjpro
HTML
<img id="sheet-mountain-creatures" src="http://80.74.112.73/~yehoshua/res/img/creatures/creature_strip_mountains.png" width="138" height="322" />
<img id="sheet-frog" src="http://80.74.112.73/~yehoshua/res/img/creatures/accordion_frog_jumps.png" />
<canvas id="c" width="1288" height="92">
CSS
img {
display: none;
}
canvas {
background-color:yellow;
}
JavaScript
function SpriteSheet(img, matrixSize, matrixCoordinates) {
this.img = img;
this.matrixSize = [];
this.matrixSize = matrixSize;
this.matrixCoordinates = [];
this.matrixCoordinates = matrixCoordinates;
var tempCanvas = document.createElement('canvas');
document.body.appendChild(tempCanvas);
this.canvas = tempCanvas;
this.canvas.style.display = 'none';
this.canvas.style.position = 'absolute';
this.canvas.style.left = -1000;
this.canvas.style.top = -1000;
this.ctx = this.canvas.getContext('2d');
}
SpriteSheet.prototype.getSprite = function (matrixCell) {
var sprite, spriteURL, x, y, width, height;
x = this.matrixCoordinates[matrixCell[0], matrixCell[1]][0];
y = this.matrixCoordinates[matrixCell[0], matrixCell[1]][1];
if (matrixCell[0] + 1 <= this.matrixSize[0]) {
width = this.matrixCoordinates[matrixCell[0] + 1, matrixCell[1]][0] - x;
} else { //last column of sprites
width = img.width - x;
}
if (matrixCell[1] + 1 <= this.matrixSize[1]) {
height = this.matrixCoordinates[matrixCell[0], matrixCell[1] + 1][1] - y;
} else { //last row of sprites
height = img.height - y;
}
this.canvas.width = width;
this.canvas.height = height;
this.ctx.drawImage(this.image, x, y, width, height, 0, 0, width, width);
spriteURL = this.canvas.toDataURL();
sprite = new Image();
sprite.src = spriteURL;
return sprite;
};
function displayImages() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var matrixSize = [13, 0];
var matrixCoordinates = [
[
[0, 0],
[92, 0],
[184, 0],
[276, 0],
[368, 0],
[460, 0],
[552, 0],
[644, 0],
[736, 0],
[828, 0],
[920, 0],
[1012, 0],
[1104, 0],
[1196, 0]
]
];
var spriteSheet,...