JS Sprite Animation
Sprite Animation
class Dog { constructor(){ // constructor method for outlining data points about the sprite this.image = document.getElementById(“dogSprite”); this.spriteWidth = SPRITE_WIDTH; this.spriteHeight = SPRITE_HEIGHT; this.width = this.spriteWidth; //takes sprite dimensions and accounts for it in image generation this.height = this.spriteHeight; this.x = 0; //starts image generation in coordinate (0,0) px on sprite sheet this.y = 0; this.scale = 1; //scale of image this.minFrame = 0; this.maxFrame = FRAME_LIMIT -1; // how many sprites there are in a row this.frameX = 0; // sets position of sprite that is being generated. There are the two parameters we will be changing in order to crete the animation. this.frameY = 0; }
draw(context) {
context.drawImage(
this.image,
this.frameX * this.spriteWidth,
this.frameY * this.spriteHeight,
this.spriteWidth,
this.spriteHeight,
this.x,
this.y,
this.width * this.scale,
this.height * this.scale
);
} }
class Dog { constructor() { this.image = document.getElementById(“dogSprite”); this.x = 0; this.y = 0; this.minFrame = 0; this.maxFrame = FRAME_LIMIT -1; this.frameX = 0; this.frameY = 0; }
// draw dog object
draw(context) {
context.drawImage(
this.image,
this.frameX * SPRITE_WIDTH,
this.frameY * SPRITE_HEIGHT,
SPRITE_WIDTH,
SPRITE_HEIGHT,
this.x,
this.y,
canvas.width,
canvas.height
);
}
// update frameX of object
update() {
if (this.frameX < this.maxFrame) {
this.frameX++;
} else {
this.frameX = 0;
}
} }
const dog = new Dog(); // This makes the game object, Dog
// Add event listener to the parent container for event delegation const controls = document.getElementById(‘controls’); controls.addEventListener(‘click’, function (event) { if (event.target.tagName === ‘INPUT’) { const selectedAnimation = event.target.id; switch (selectedAnimation) { case ‘RightWalk’: dog.frameY = 0; break; case ‘RightRun’: dog.frameY = 1; break; case ‘DownWalk’: dog.frameY = 2; break; case ‘DownRun’: dog.frameY = 3; break; default: break; } } });
// Animation recursive control function function animate() { // Clears the canvas to remove the previous frame. ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draws the current frame of the sprite.
dog.draw(ctx);
// Updates the `frameX` property to prepare for the next frame in the sprite sheet.
dog.update();
// Uses `requestAnimationFrame` to synchronize the animation loop with the display's refresh rate,
// ensuring smooth visuals.
requestAnimationFrame(animate); }
animate();
%%html