You could create a function to get the tile position and size based on the spritesheet layout. This makes these sort of things easier to handle. Provide index [0, 15] and you'll get back an object with the tile's position:
function getTile(index) {
var row = (index / 4)|0, // line
col = index % 4, // column
w = 50, // tile width and height
h = 50;
return {
x: col * w,
y: row * h,
w: w,
h: h
}
}
The drawImage()
method works this way (for this overload):
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
where s* are the source coordinates in your spritesheet, and d* is destination position and size for the clipped region you get from the s* coordinates.
So here you could do:
var width = 50,
height = 50,
frames = 16,
currentFrame = 0,
canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d"),
image = new Image();
image.onload = function() {
setInterval(draw, 400); // start when image has finished loading
}
image.src = "sprites.png"
function draw(){
ctx.clearRect(0, 0, width, height);
var tile = getTile(currentFrame);
ctx.drawImage(image, tile.x, tile.y, tile.w, tile.h, 0, 0, width, height);
currentFrame++;
if (currentFrame === frames) {
currentFrame = 0;
}
}