Tile-based maps and environments. Map data with layers, loading Tiled (mapeditor.org) JSON with tile properties and object layers (spawns, triggers), ASCII maps for quick levels and tests, solid and special tiles, world ↔ tile conversion, 4-bit and 47-tile blob autotiling, chunked render caches with culling so big maps stay fast, editing tiles at runtime, and tileset conventions. Includes teste...
Download skill (.zip) Files on GitHubTilemap development
Drop-in: assets/tilemap.js (tests: solids and bounds, properties, Tiled import with flip bits stripped and objects,
autotile masks (47 blob variants), chunk caching, edits redraw only their chunk; rendered in a browser).
import { TileMap, tileset, fromTiled, fromAscii, autotile4 } from "./core/tilemap.js";
const map = fromTiled(await (await fetch("assets/data/level-01.json")).json()); // tiles with a "solid" property collide
const tiles = tileset(images.tiles, 16);
const spawn = map.objectsOfType("spawn").find((o) => o.props.who === "player");
// physics: moveAndSlide(body, dx, dy, (c, r) => map.isSolid(c, r), map.tileSize) (game-physics)
// draw (world space, after camera.apply):
map.draw(ctx, "ground", tiles, camera.view(16)); // cached 16×16-tile chunks, only visible ones
map.set("ground", c, r, -1); // break a block: only that chunk redraws
const quick = fromAscii(["#####", "#..^#", "#####"], { "#": 0, "^": 5 }, 16, { solidTiles: [0], tileProps: { 5: { hurts: true } } });
Tiled tips
- Orthogonal map, tile layer format CSV (not compressed), embedded tilesets (or load the external one and merge).
- Tile properties:
solid,oneWay,hurts,ladder. Object layer: spawns, doors, triggers, camera bounds (with custom properties). - Layers:
background,ground(collision),foreground(drawn over the player),objects.
Autotiling
autotile4(same, c, r) → 0–15 for simple edges (paths, water). autotile8 → masks that reduce to the 47 blob variants for
full terrain sets; map them to your tileset’s ids with a lookup table. Run it once at load (or for neighbors after an edit).
Performance
- Chunk caches turn thousands of
drawImagecalls into a few per frame. Keep chunks ~256–512 px. imageSmoothingEnabled = falseand integer camera positions for crisp pixel tiles (camera-systempixelSnap).- Seams between tiles at fractional zoom: add 1-px extruded padding in the tileset (Tiled “margin/spacing”) or snap the camera.
Conventions
Tile size 16 or 32 px; tileset PNG power-of-two width; tile id -1 = empty; level files in assets/data/levels/, named
level-01.json. Validate levels in tests (reachability with pathfinding, spawn exists).