# How to display a tile map from a 2D array in JavaScript?

I have stored my map, but the problem I am having is displaying it. My map is 100x100 tiles which are 40x40px.

I have my loop running through the array but I'm having difficulty selecting the portion of the map image to relate to the tiles. This is the code which selects the portion of the image on each iteration:

var sx = Math.floor(tileId % 8 * tileWidth); //source x
var sy = Math.floor(tileId / 8 * tileHeight); //source y


I'm using Canvas and keep getting this error message:

INDEX_SIZE_ERR: DOM Exception 1: Index or size was negative, or greater than the allowed value.


I'm guessing the remainder or division by 8 is wrong, this is something I picked up from the net, but what exactly does that integer need to be?

Thanks

If you're using sx and sy to index into your array then they indeed will be out of bounds rather quickly. Since the tileWidth and tileHeight have nothing to do with how the tiles are indexed.

You can index into your array with the following:

var sx = Math.floor(tileId % 8); //source x -- don't actually need floor here
var sy = Math.floor(tileId / 8); //source y -- this is really just cast to int


I'm assuming that your tileID is a number from 0 to 9,999 (one for each tile in a 100x100 grid). EDIT

I fixed the image above to correct the TileStartX column.

If you want 16x12 tiles you won't be able to do it with an index ranging from 1 to 100. You need 1 to 192 (i.e. 16*12=192). Additionally, for the xIndex you need to mod the tileID by 16, not 8. Likewise you need to divide the tileID by 16 to get the yIndex. So indexing tile 60 in a 16 by 12 grid would be:

60%16 = 12
60/16 = 3


So in your array you'd get tile tiles Or the tile in column 12 of row 3. Then if you wanted to draw that tile you'd draw it at X=12*40=480 Y=3*40=120 So you'd draw tile tiles at x=480,y=120.

• Hey, thanks for the answer, I can see how the % and division is working now, but I'm still having a bit of a problem, my tileID represents a number between 1 and 100, each for a separate 40x40 portion of an image. So I need to find out how to map the tileID 60 to the portion of the image/sprite which it needs to display – Sabai Apr 29 '12 at 17:30
• The image sprite is 16x12 tiles, each 40x40, if that helps – Sabai Apr 29 '12 at 17:37
• Excellent, thank you, especially for that table which really indicated how the math works there. I eventually got my head around it! – Sabai Apr 29 '12 at 20:52