JSFiddle - React, Tailwind, and code Playground
HTML
<canvas></canvas>
<img src="https://image.noelshack.com/fichiers/2017/22/1496497496-mario.png" alt="mario" />
JavaScript
var canvas = document.querySelector('canvas');
canvas.height = 400;
canvas.width = 400;
var context = canvas.getContext('2d');
context.imageSmoothingEnabled = false;
var myspritesheet = document.querySelector('img');
function Sprite(model) {
this.image = model.image;
this.frames = model.frames;
this.ticksPerFrame = model.ticksPerFrame;
this.width = this.image.width;
this.height = this.image.height;
this.frameW = this.width / model.frames;
this.frameIndex = 0;
this.tickCount = 0;
}
Sprite.prototype.update = function (x, y) {
this.tickCount += 1;
if (this.tickCount > this.ticksPerFrame) {
this.tickCount = 0;
if (this.frameIndex < this.frames - 1) {
this.frameIndex += 1;
} else {
this.frameIndex = 0;
}
}
context.drawImage(
this.image,
this.frameIndex * this.frameW,
0,
this.frameW,
this.height,
x,
y,
this.frameW * 2, //render 2x bigger
this.height * 2 //render 2x bigger
);
};
var mario = new Sprite({
image: myspritesheet,
frames: 6,
ticksPerFrame: 4
});
function loop() {
context.clearRect(0,0,400,400);
mario.update(100, 100);
requestAnimationFrame(loop);
}
loop();