# How to draw a tileset using HTML5 canvas?

I have a tileset something like this:

0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16,
17, 18, 19, 20


My tileset draw code looks like this:

var image = new Image();
image.src = '32x32.png';
var tile = 5;
var tileSize = 32;
var x = 100;
var y = 100;
context.drawImage(image, Math.floor(tile * tileSize), 0, tileSize, tileSize, x, y, tileSize, tileSize);


And this code draws the 5 tile, but how would I draw the 10 tile, or the 15 tile without adding tileX and tileY? I probably need something like if tile is equal to 15, then draw tile 15.

I'm not sure I understand why adding tileX and tileY is a bad thing? If you want to draw the whole tileset, one way of doing it is with a couple of for loops like so.

var tileSize = 32;
var x = 10;
var y = 10;

for(var tileX = 0; tileX < x; tileX ++) {
for(var tileY = 0; tileY < y; tileY++) {
context.drawImage(image, tileX * tileSize,tileY * tileSize , tileSize, tileSize);
}
}


JSFiddle Example

Just my preference, but the naming below might make things a bit more clear as well.

var tileSize = 32;
var width = 10;
var height = 10;

for(var x = 0; x < width ; x++) {
for(var y = 0; y < height; y++) {
context.drawImage(image, x * tileSize, y * tileSize , tileSize, tileSize);
}
}


Hope that helps.

You can add tileX and tileY but hide them inside a function where they won't trouble you.

var drawTile = function (tile, x, y, tileSize) {
var tileX = tile % 6; //6 is the number of tiles in each row
var tileY = Math.floor(tile/6);
context.drawImage(image, tileX * tileSize, tileY * tileSize, tileSize, tileSize, x, y, tileSize, tileSize);
};


Now you can draw any of the tiles just by giving its number:

var image = new Image();
image.src = '32x32.png';
var tile = 5;
var tileSize = 32;
var x = 100;
var y = 100;
drawTile(tile, x, y, tileSize);
tile = 10;
x = 200;
y= 100;
drawTile(tile, x, y, tileSize);