%%html
<title>Javascript Hack 2: Sprites</title>
<canvas id="newCanvas"></canvas>
<script>
// Sprite sheet with calculated frame width, height, and count
const sprite = {
src: "https://tse1.mm.bing.net/th?q=fire%20sprite%20sheet",
frameWidth: 94.8,
frameHeight: 94.8,
framesPerRow: 5,
frameCount: 25
};
// Create canvas and context
const canvas = document.getElementById("newCanvas");
canvas.width = sprite.frameWidth;
canvas.height = sprite.frameHeight;
const context = canvas.getContext("2d");
const image = new Image();
image.src = sprite.src;
// Define variables and determine the speed of the sprite animation
let frame = 0;
let frameRate = 25;
let frameCount = 0;
// displayMovingSprite function
function displayMovingSprite() {
const column = frame % sprite.framesPerRow;
const row = Math.floor(frame / sprite.framesPerRow);
context.clearRect(0 , 0, canvas.width, canvas.height);
context.drawImage(
image,
//x and y coordinates of the sprite sheet
column * sprite.frameWidth,
row * sprite.frameHeight,
sprite.frameWidth,
sprite.frameHeight,
0, 0,
sprite.frameWidth,
sprite.frameHeight
);
frameCount++;
if (frameCount >= frameRate) {
frame = (frame + 1) % sprite.frameCount;
frameCount = 0;
}
requestAnimationFrame(displayMovingSprite)
}
image.onload = displayMovingSprite;
</script>