Tile Maps in 2D Games

how to make a tilemap

If you want to know how to make a tilemap, store the level as a 2D array of tile numbers, draw each tile from one tileset image with drawImage, and convert pixel positions to columns and rows for collision.

The steps below start from a hand-written grid and end with a level that draws and blocks movement. They are one building block of 2d game programming for beginners, so each step stays small enough to test before you add the next.

What a tile map is and why games use one

A tile map stores a level as a grid of numbers, where each number is the index of the sprite to draw at that cell. In the HTML canvas tile map walkthrough this article follows, each number represents the index into the sprite atlas used when drawing that tile, and the atlas is a single image holding all the sprites.

That arrangement suits small browser games for practical reasons. The level is plain data you can edit by hand, and the same grid that drives drawing also answers questions such as “is the cell to my right solid?”. Choose a tile map when your world is built from repeating square pieces. If your art is one large painted scene, a tile map adds little.

The floor shows a repeating herringbone pattern of small rectangular tiles.

Storing the level as a 2D array

A 2D array is the natural container: one inner array per row, one entry per column. Building or reading it is a nested loop over rows and columns, which is the usual way people approach a tile map in code.

Sketch the grid first

Before typing anything, rule out a grid on paper and write a tile number in each cell. The paper grid is the array, row for row, so typos are easy to spot and a level is quick to rearrange. Give each tile a short name in code so the array stays readable, with each constant standing for that tile’s position in the tileset.

A small level then looks like this in code, with each constant defined as the index of its tile in the tileset:

const level = [
  [WALL, WALL, WALL, WALL],
  [WALL, GRASS, GRASS, WATER],
  [WALL, GRASS, WALL, WATER]
];

Read a tile with level[row][col], row first, because the outer array holds the rows.

Pick a tile size and keep it fixed

Tile size is the width and height of one square tile in pixels, and it is stored once for the whole map. The example in the walkthrough uses a tile size of 16 pixels with a 16 by 16 grid, loaded from a tileset image cut into 16-pixel tiles. Every other calculation here multiplies or divides by that single number, so the tileset image and the map must agree on it.

  • Start small: a modest grid with one tile size is enough to prove drawing and collision before you design real levels.
  • Change it in one place: keep tile size as a constant, never a literal repeated through the code.
  • Match the art: if the tileset tiles are not the same size as the constant, drawn tiles will show slivers of their neighbours or cut-off edges.

Drawing the tile that matches each array value

The tileset is one image containing every tile, and you draw a single tile from it by naming a source rectangle. That is exactly what the canvas drawImage method does when you give it both a source and a destination rectangle. The walkthrough passes the parameters named sx, sy, sWidth and sHeight for the slice of the atlas, and dx, dy, dWidth and dHeight for where it lands on the canvas.

Graph-ruled paper makes a convenient planning surface: each ruled cell can hold one tile number, and each written row becomes one inner array.

In the full form, the call reads ctx.drawImage(tileset, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight). For a tile, both widths and both heights equal the tile size. Getting the two rectangles is a matter of converting an index into a column and row, then scaling by tile size.

  1. Find the tile’s place in the tileset. Given an index, the column is the index modulo the number of columns, and the row is the index divided by the number of columns, rounded down. That is the same index-to-row-and-column conversion a 2D array uses.
  2. Turn that place into source pixels. Multiply the tileset column and row by tile size to get sx and sy.
  3. Turn the map cell into destination pixels. Multiply the map column and row by tile size to get dx and dy, as in the walkthrough’s x = col * tileSize and y = row * tileSize.
  4. Draw once per cell. Loop over every row and column, read the value, and make one drawImage call.

Put together:

level.forEach((rowTiles, row) => {
  rowTiles.forEach((id, col) => {
    const sx = (id % tilesetCols) * tileSize;
    const sy = Math.floor(id / tilesetCols) * tileSize;
    ctx.drawImage(tileset, sx, sy, tileSize, tileSize,
      col * tileSize, row * tileSize, tileSize, tileSize);
  });
});

Wait for the tileset image to finish loading before running this loop, otherwise the first draw has nothing to cut from.

Keeping the game loop cheap

A static map does not need to be rebuilt on every frame. Forum advice on building a tile map from nested loops, in a Codea community thread, is to draw the map into an image once in setup and reuse it. In a browser game the same idea means running the drawing loop above once, then having your game loop paint that finished picture each frame before drawing the player and other moving objects on top.

Whether the map is pre-drawn depends on how the level behaves. If tiles never change, pre-draw it. If doors open or blocks are destroyed, redraw the affected cells or refresh the picture when the array changes. When a level is only one screen among menus and pause states, game state management decides which state runs the map-drawing code.

Converting between pixel position and tile column and row

Tile to pixel is multiplication by tile size, and pixel to tile is the reverse: divide by tile size and round down. The walkthrough gives the forward direction, x = col * tileSize and y = row * tileSize, and the inverse follows directly. Canvas coordinates are measured in canvas coordinate space units, as MDN’s canvas pixel manipulation tutorial notes, so keep positions and tile size in the same coordinate space.

An evenly spaced grid of identical squares is the shape a tileset image takes: every tile occupies a cell, and a tile’s index tells you which cell to cut.

Using the conversion for collision

Collision becomes a lookup. Convert the point you care about, such as a corner of the player’s box at its next position, into a column and row, read level[row][col], and refuse the move if that tile is on your solid list. Because the grid already holds every tile, there is no need to compare the player against each wall rectangle.

The stones are uneven in shape and size, with darker gaps between them.
  • Keep a solid list: name which tile types block movement, so walls and water can be treated differently from grass.
  • Test the destination, not the current spot: check the cell the player is about to enter before committing the move.
  • Test every corner: a box can overlap a wall tile with only one corner, so convert each corner you care about.
  • Keep input separate: whether movement comes from the keyboard or from gamepad api javascript, the collision test only needs the proposed position.

Troubleshooting a tile map that looks wrong

Most tile map bugs come from mixing up columns and rows, forgetting tile size, or cutting the wrong slice from the tileset. Match what you see to the first column below.

What you see Likely cause What to change
Tiles are drawn in the wrong place or all bunched together Column and row used as pixel positions without scaling Multiply by tile size: x = col * tileSize, y = row * tileSize.
Level looks mirrored or rotated Row and column swapped when reading the array Index the array row first, then column.
Wrong tile image appears for a value Index-to-column-and-row conversion is off Use column = index modulo number of columns and row = index divided by number of columns, rounded down.
Tile shows pieces of neighbouring tiles Source width or height differs from the tile size in the tileset Pass the tile size as both sWidth and sHeight, and make the art match.
Frame rate drops as the map grows Static map redrawn cell by cell on every frame Draw the map once into an image and paint that image each frame.

The formulas in this table come from the canvas tile map walkthrough, and the draw-once advice comes from the Codea thread.

Once the array, the draw loop and the pixel conversion each work on their own, you can scale up to bigger levels. A visual map editor can then paint the grid for you, as long as you load its output into the same row-by-column array shape that your drawing and collision code already expects.

A stand-in for solid wall tiles: in a tile map, any cell whose tile is on the solid list blocks movement, however the art looks.

Frequently asked questions

Question Answer
Can I pre-draw the map onto a canvas and use that as the image? Yes. As this canvas cheatsheet points out, drawImage accepts a canvas element as its image source, so a second canvas can hold the finished map.
Can a tileset have more than one row? Yes, provided you split an index into a column and row. The example the walkthrough uses supports only a single row of images, so a multi-row tileset needs the modulo-and-divide conversion instead.
What units are tile size and positions in? Tile size is stored in pixels, and canvas positions are in canvas coordinate space units, so treat them as one coordinate space for conversions.
Do I have to write the array by hand? No. Hand-writing suits small test levels, and a visual editor is the better choice once levels get large, provided it loads into the same array of tile numbers.