改變刺蝟的方向
(function() {
var hedgehogImage, canvas;
class sprite {
constructor({
context,
width,
height,
image,
ticksPerFrame,
numberOfFrames
}) {
this.context = context;
this.width = width;
this.height = height;
this.image = image;
this.frameIndex = 0;
this.tickCount = 0;
this.ticksPerFrame = ticksPerFrame || 0;
this.numberOfFrames = numberOfFrames || 1;
}
update = () => {
// this.context.scale(-1, 1);
this.tickCount += 1;
if (this.tickCount > this.ticksPerFrame) {
this.tickCount = 0;
// If the current frame index is in range
if (this.frameIndex < this.numberOfFrames - 1) {
// Go to the next frame
this.frameIndex += 1;
} else {
this.frameIndex = 0;
}
}
};
render = () => {
// Clear the canvas
this.context.clearRect(0, 0, this.width, this.height);
this.context.scale(-1, 1);
this.context.drawImage(this.image, -this.image.width, 0);
// Draw the animation
this.context.drawImage(
this.image,
(this.frameIndex * this.width) / this.numberOfFrames,
0,
this.width / this.numberOfFrames,
this.height,
0,
0,
this.width / this.numberOfFrames,
this.height
);
// this.context.scale(-1, 1);
};
}
// Get canvas
canvas = document.getElementById("hedgehog");
canvas.width = 269;
canvas.height = 351;
// Create sprite sheet
hedgehogImage = new Image();
// Create sprite
hedgehog = new sprite({
context: canvas.getContext("2d"),
width: 1615,
height: 351,
image: hedgehogImage,
numberOfFrames: 6,
ticksPerFrame: 10
});
function gameLoop() {
window.requestAnimationFrame(gameLoop);
hedgehog.update();
hedgehog.render();
hedgehog.context.scale(-1, 1)
}
// Load sprite sheet
hedgehogImage.addEventListener("load", gameLoop);
hedgehogImage.src = "https://i.imgur.com/JKPX5Zs.png";
})();