DEV Community

Seed Map
Seed Map

Posted on

Building a Map Legend from Your Tile Data (Canvas + JS)

If you render any kind of tile map on a canvas (game worlds, heatmaps, land-use data) you will eventually need a legend that maps colours to categories. A good legend is generated from the same data as the map, so the two never drift apart. Here is a compact approach using a Minecraft-style biome palette as the example.

Keep one source of truth

const BIOMES = {
  plains:        { id: 1,  color: "#8db360", label: "Plains" },
  desert:        { id: 2,  color: "#fa9418", label: "Desert" },
  forest:        { id: 4,  color: "#056621", label: "Forest" },
  taiga:         { id: 5,  color: "#0b6659", label: "Taiga" },
  swamp:         { id: 6,  color: "#07f9b2", label: "Swamp" },
  ocean:         { id: 0,  color: "#000070", label: "Ocean" },
  cherry_grove:  { id: 185, color: "#ffb7c5", label: "Cherry Grove" },
};
const byId = new Map(Object.values(BIOMES).map(b => [b.id, b]));
Enter fullscreen mode Exit fullscreen mode

The renderer and the legend both read from BIOMES. Add a biome once and it appears in both places.

Render tiles from ids

function drawTiles(ctx, grid, size) {
  for (let y = 0; y < grid.length; y++) {
    for (let x = 0; x < grid[y].length; x++) {
      ctx.fillStyle = byId.get(grid[y][x])?.color ?? "#ff00ff";
      ctx.fillRect(x * size, y * size, size, size);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Magenta for unknown ids makes missing palette entries impossible to miss during development.

Build the legend from what is visible

Showing every category is noisy. List only the ones currently on screen, sorted by how much area they cover:

function visibleLegend(grid) {
  const counts = new Map();
  for (const row of grid) for (const id of row) counts.set(id, (counts.get(id) || 0) + 1);
  return [...counts].sort((a, b) => b[1] - a[1])
    .map(([id]) => byId.get(id)).filter(Boolean);
}

function renderLegend(el, items) {
  el.innerHTML = items.map(b =>
    `<li><span style="background:${b.color}"></span>${b.label}</li>`).join("");
}
Enter fullscreen mode Exit fullscreen mode

Call renderLegend after every pan or zoom, debounced to about 100 ms.

Accessibility notes

  • Colour alone isn't enough: show the label on hover or tap, and include the name in the legend text.
  • Check contrast for the legend swatches against your background; very light biomes such as Cherry Grove disappear on white without a border.
  • Keep the legend as real HTML text, not part of the canvas, so screen readers can read it.

Seeing it in a real tool

If you want to see a biome legend like this working on actual Minecraft worlds, this tool colours biomes for any seed and lets you jump to a specific one. It's a good reference for how a dense palette can still stay readable.

Top comments (0)