Tiled, LDtk & Aseprite
Typing levels as arrays of strings works for a lesson, but a real game needs dozens of levels and hundreds of animation frames. Three free or cheap tools have become the standard for 2D indie games: Tiled and LDtk for levels, Aseprite for pixel art and animation. All three export plain JSON, which your game reads with fetch + JSON.parse. This lesson shows what those files look like and how to read them.
| Tool | What it makes | Price | Export used by games |
|---|---|---|---|
| Tiled | Tile maps of any kind: layers, objects, properties | Free, open source | .tmj (JSON) or .tmx (XML) |
| LDtk | 2D levels with a strong focus on platformers and top-down games; auto-tiling rules | Free, open source | .ldtk (JSON), optional per-level files and PNG layers |
| Aseprite | Pixel-art sprites, animation frames and tags | Paid (source available; you can compile it yourself) | Sprite sheet .png + .json with frames and tags |
Tiled maps
A Tiled map is a grid of tile ids organised in layers, plus object layers for things that are not tiles (spawn points, triggers, enemies). Tile images come from tilesets. Saved as JSON (.tmj), a small map looks like this:
{
"width": 6, "height": 3, "tilewidth": 16, "tileheight": 16, "orientation": "orthogonal", "infinite": false,
"tilesets": [
{ "firstgid": 1, "name": "terrain", "image": "terrain.png", "columns": 8, "tilecount": 64, "tilewidth": 16, "tileheight": 16 },
{ "firstgid": 65, "name": "props", "image": "props.png", "columns": 4, "tilecount": 16, "tilewidth": 16, "tileheight": 16 }
],
"layers": [
{ "type": "tilelayer", "name": "ground", "width": 6, "height": 3, "data": [0, 0, 0, 0, 0, 0, 0, 66, 0, 0, 2147483714, 0, 1, 1, 2, 2, 1, 1] },
{ "type": "objectgroup", "name": "entities", "objects": [
{ "id": 1, "name": "spawn", "x": 16, "y": 16, "width": 16, "height": 16, "properties": [{ "name": "lives", "type": "int", "value": 3 }] }
] }
]
}Key facts:
datais the grid, row by row (index = row * width + col).0means "no tile".- The numbers are global tile ids (gids). Each tileset owns a range starting at its
firstgid. To find the tile, take the tileset with the largestfirstgidthat is ≤ the gid; the local index isgid - firstgid. - The top bits of a gid are flip flags:
0x80000000horizontal,0x40000000vertical,0x20000000diagonal (anti-diagonal flip, used for 90° rotations), and0x10000000for hexagonal rotation. Clear them withgid & 0x0fffffffbefore looking up the tile. The value2147483714above is0x80000000 + 66: tile 66, mirrored horizontally. - Object coordinates are in pixels, not tiles. Custom properties are an array of
{ name, type, value }. - Large maps may store
dataas base64 (optionally compressed) instead of a plain array; pick "CSV" layer format in the map properties to keep plain arrays.
const map = {
width: 6, height: 3,
tilesets: [{ firstgid: 1, name: 'terrain' }, { firstgid: 65, name: 'props' }],
layers: [
{ type: 'tilelayer', name: 'ground', data: [0, 0, 0, 0, 0, 0, 0, 66, 0, 0, 2147483714, 0, 1, 1, 2, 2, 1, 1] },
{ type: 'objectgroup', name: 'entities', objects: [{ name: 'spawn', x: 16, y: 16, properties: [{ name: 'lives', type: 'int', value: 3 }] }] },
],
};
const FLIP_H = 0x80000000, FLIP_V = 0x40000000, FLIP_D = 0x20000000;
function decodeGid(raw) {
const gid = raw & 0x0fffffff;
if (gid === 0) return null;
const tileset = map.tilesets.filter((t) => t.firstgid <= gid).at(-1);
return {
tileset: tileset.name,
local: gid - tileset.firstgid,
flipH: (raw & FLIP_H) !== 0,
flipV: (raw & FLIP_V) !== 0,
flipD: (raw & FLIP_D) !== 0,
};
}
const ground = map.layers.find((l) => l.name === 'ground');
ground.data.forEach((raw, i) => {
const t = decodeGid(raw);
if (!t) return;
const col = i % map.width, row = Math.floor(i / map.width);
const flips = [t.flipH && 'H', t.flipV && 'V', t.flipD && 'D'].filter(Boolean).join('') || '-';
console.log(`(${col},${row}) ${t.tileset}#${t.local} flip:${flips}`);
});
const props = (obj) => Object.fromEntries((obj.properties ?? []).map((p) => [p.name, p.value]));
const spawn = map.layers.find((l) => l.type === 'objectgroup').objects.find((o) => o.name === 'spawn');
console.log('spawn at tile', spawn.x / 16, spawn.y / 16, props(spawn));(1,1) props#1 flip:-
(4,1) props#1 flip:H
(0,2) terrain#0 flip:-
(1,2) terrain#0 flip:-
(2,2) terrain#1 flip:-
(3,2) terrain#1 flip:-
(4,2) terrain#0 flip:-
(5,2) terrain#0 flip:-
spawn at tile 1 1 { lives: 3 }
LDtk levels
LDtk ("Level Designer Toolkit", by one of the Dead Cells developers) organises a project into levels, each with layer instances of four kinds:
| Layer type | Holds | Typical use |
|---|---|---|
IntGrid |
A grid of small integers (1 = wall, 2 = water...) | Collision, game logic |
AutoLayer |
Tiles generated from an IntGrid by rules | Pretty walls and corners without hand-placing tiles |
Tiles |
Hand-placed tiles | Decoration |
Entities |
Objects with typed fields | Player start, enemies, doors, keys |
A trimmed level from a .ldtk file:
{
"identifier": "Level_0", "pxWid": 256, "pxHei": 128,
"layerInstances": [
{ "__identifier": "Entities", "__type": "Entities", "__gridSize": 16,
"entityInstances": [ { "__identifier": "Player", "__grid": [2, 5], "px": [32, 80],
"fieldInstances": [ { "__identifier": "lives", "__type": "Int", "__value": 3 } ] } ] },
{ "__identifier": "Collisions", "__type": "IntGrid", "__cWid": 16, "__cHei": 8, "__gridSize": 16,
"intGridCsv": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
"autoLayerTiles": [ { "px": [0, 112], "src": [16, 0], "f": 0, "t": 1 } ] }
]
}Fields starting with __ are convenience copies that LDtk writes for game code. intGridCsv is your collision map, exactly like the tilemap arrays in Platformer 2. Each auto-layer tile gives its pixel position px, its source position in the tileset image src and flip bits f (1 = X, 2 = Y), so drawing it is one drawImage call.
Tip: Tiled is the generalist (any genre, isometric and hexagonal maps, huge plugin ecosystem, supported by Phaser's tilemap loader). LDtk is more opinionated and faster for side-view and top-down levels thanks to auto-layers and typed entities. Both have importers for Godot, Unity and most web frameworks.
Aseprite sprite sheets
Aseprite draws pixel art in frames and groups frames into tags (idle, run, jump). File → Export Sprite Sheet packs the frames into one PNG and writes a JSON file that describes where each frame is, how long it lasts and which tags exist:
const sheet = {
frames: [
{ frame: { x: 0, y: 0, w: 16, h: 16 }, duration: 300 },
{ frame: { x: 16, y: 0, w: 16, h: 16 }, duration: 300 },
{ frame: { x: 32, y: 0, w: 16, h: 16 }, duration: 100 },
{ frame: { x: 48, y: 0, w: 16, h: 16 }, duration: 100 },
{ frame: { x: 64, y: 0, w: 16, h: 16 }, duration: 100 },
],
meta: {
image: 'hero.png',
frameTags: [
{ name: 'idle', from: 0, to: 1, direction: 'forward' },
{ name: 'run', from: 2, to: 4, direction: 'pingpong' },
],
},
};
// Which frame of a tag is visible after `ms` milliseconds (looping)?
function frameAt(tagName, ms) {
const tag = sheet.meta.frameTags.find((t) => t.name === tagName);
let order = [];
for (let i = tag.from; i <= tag.to; i++) order.push(i);
if (tag.direction === 'pingpong') order = order.concat(order.slice(1, -1).reverse()); // 2 3 4 3
if (tag.direction === 'reverse') order.reverse();
const total = order.reduce((sum, i) => sum + sheet.frames[i].duration, 0);
let t = ms % total;
for (const i of order) {
if (t < sheet.frames[i].duration) return i;
t -= sheet.frames[i].duration;
}
}
for (const ms of [0, 250, 350, 650]) console.log(`idle @${ms}ms -> frame ${frameAt('idle', ms)}`);
const run = [0, 100, 200, 300, 400].map((ms) => frameAt('run', ms));
console.log('run frames every 100 ms:', run.join(' '));
const f = sheet.frames[frameAt('run', 150)].frame;
console.log(`drawImage(img, ${f.x}, ${f.y}, ${f.w}, ${f.h}, x, y, ${f.w}, ${f.h})`);idle @0ms -> frame 0
idle @250ms -> frame 0
idle @350ms -> frame 1
idle @650ms -> frame 0
run frames every 100 ms: 2 3 4 3 2
drawImage(img, 48, 0, 16, 16, x, y, 16, 16)
Per-frame durations matter: the idle animation holds each frame for 300 ms while running frames last 100 ms. Using Aseprite's own timing keeps the animation exactly as the artist drew it. Export with "Trim" off (or read the spriteSourceSize fields) so frames keep a stable size, and with a 1–2 px padding to avoid neighbouring frames bleeding in when scaled.
Playable: rendering a tile map with flips and objects
The map below is stored the way Tiled stores it: a flat data array of gids with flip bits, plus an object layer. The tileset image is drawn in code on an off-screen canvas, so no files are needed. Use the arrow keys to scroll the camera. The counter shows that only the tiles on screen are drawn (culling). Notice the arrow signs: there is only one arrow tile; the left-pointing ones use the horizontal flip flag.
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set(); // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
if (!e.repeat) pressed.add(e.code);
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
ctx.save();
ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
ctx.restore();
}
function run(update, draw, help = '') {
const STEP = 1 / 60;
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
if (active) {
acc += dt;
while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
draw();
} else if (!idleDrawn) {
draw(); banner('Click to play', help); idleDrawn = true;
}
requestAnimationFrame(frame);
});
}
// ---- end of play kit ----
// ---- a tileset drawn in code: 6 tiles of 16x16 ----
const TS = 16;
const tileset = document.createElement('canvas');
tileset.width = TS * 6; tileset.height = TS;
const t = tileset.getContext('2d');
t.fillStyle = '#5d4037'; t.fillRect(0, 0, 16, 16); t.fillStyle = '#66bb6a'; t.fillRect(0, 0, 16, 5); // 1 grass
t.fillStyle = '#5d4037'; t.fillRect(16, 0, 16, 16); t.fillStyle = '#4e342e'; t.fillRect(20, 6, 3, 3); t.fillRect(26, 11, 3, 3); // 2 dirt
t.fillStyle = '#8d6e63'; t.fillRect(32, 0, 16, 16); t.fillStyle = '#6d4c41'; t.fillRect(32, 7, 16, 2); t.fillRect(39, 0, 2, 7); // 3 brick
t.fillStyle = '#795548'; t.fillRect(55, 8, 2, 8); t.fillStyle = '#ffca28'; t.fillRect(49, 2, 12, 6);
t.fillStyle = '#ffca28'; t.beginPath(); t.moveTo(61, 0); t.lineTo(64, 5); t.lineTo(61, 10); t.fill(); // 4 arrow sign (points right)
t.fillStyle = '#b0bec5'; t.beginPath(); t.moveTo(64, 16); t.lineTo(68, 6); t.lineTo(72, 16); t.lineTo(76, 6); t.lineTo(80, 16); t.fill(); // 5 spikes
t.fillStyle = '#4fc3f7'; t.fillRect(80, 0, 16, 16); t.fillStyle = '#81d4fa'; t.fillRect(80, 2, 16, 2); // 6 water
// ---- the map, in Tiled's format (built from strings to keep the lesson short) ----
const FLIP_H = 0x80000000;
const rows = [
'........................................................',
'........................................................',
'........................................................',
'..........................BBB...........................',
'........................................................',
'...............BBBB..................BBBB...............',
'........................................................',
'.....>......................<...........>........<......',
'##########...#######^^^#######...#####~~~~#######..#####',
'==========...==========================~~~=======..=====',
];
const GID = { '#': 1, '=': 2, 'B': 3, '>': 4, '<': 4 | FLIP_H, '^': 5, '~': 6 };
const map = {
width: rows[0].length, height: rows.length, tilewidth: TS, tileheight: TS,
layers: [
{ type: 'tilelayer', name: 'ground', data: rows.join('').split('').map((ch) => (GID[ch] ?? 0) >>> 0) },
{ type: 'objectgroup', name: 'entities', objects: [
{ name: 'spawn', x: 32, y: 112 }, { name: 'coin', x: 248, y: 64 }, { name: 'coin', x: 616, y: 64 }, { name: 'goal', x: 856, y: 112 },
] },
],
};
const ground = map.layers[0], objs = map.layers[1].objects;
const mapW = map.width * TS, mapH = map.height * TS;
const OFFSET_Y = H - mapH; // stand the map on the bottom of the screen
let camX = 0, drawn = 0;
function update(dt) {
if (keys.has('ArrowLeft')) camX -= 200 * dt;
if (keys.has('ArrowRight')) camX += 200 * dt;
camX = Math.max(0, Math.min(mapW - W, camX));
}
function drawTile(raw, x, y) {
const gid = raw & 0x0fffffff;
const sx = (gid - 1) * TS; // firstgid = 1
if (raw & FLIP_H) {
ctx.save();
ctx.translate(x + TS, y);
ctx.scale(-1, 1); // mirror horizontally
ctx.drawImage(tileset, sx, 0, TS, TS, 0, 0, TS, TS);
ctx.restore();
} else {
ctx.drawImage(tileset, sx, 0, TS, TS, x, y, TS, TS);
}
}
function draw() {
ctx.fillStyle = '#1e3a5f';
ctx.fillRect(0, 0, W, H);
const cx = Math.round(camX);
const firstCol = Math.floor(cx / TS), lastCol = Math.min(map.width - 1, Math.floor((cx + W) / TS));
drawn = 0;
for (let row = 0; row < map.height; row++) {
for (let col = firstCol; col <= lastCol; col++) {
const raw = ground.data[row * map.width + col];
if (!raw) continue;
drawTile(raw, col * TS - cx, OFFSET_Y + row * TS);
drawn++;
}
}
for (const o of objs) {
const x = o.x - cx, y = OFFSET_Y + o.y;
ctx.fillStyle = o.name === 'spawn' ? '#ffb74d' : o.name === 'goal' ? '#e040fb' : '#ffd54f';
if (o.name === 'coin') { ctx.beginPath(); ctx.arc(x + 8, y + 8, 5, 0, Math.PI * 2); ctx.fill(); }
else ctx.fillRect(x + 2, y, 12, 16);
}
ctx.fillStyle = '#fff';
ctx.font = '12px monospace';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.fillText(`camera x ${cx} tiles drawn ${drawn} of ${ground.data.filter(Boolean).length}`, 8, 8);
}
run(update, draw, 'Arrow keys scroll the map');
</script>Workflow tips
- Keep the exported JSON in your repository next to the source files (
.tmx/.tmj,.ldtk,.aseprite), and re-export with a script or the tools' command-line modes (aseprite -b hero.aseprite --sheet hero.png --data hero.json --list-tags) so builds are reproducible. - Use custom properties / fields for gameplay data (enemy speed, door targets, checkpoint ids) instead of hard-coding it by position.
- Pack all small images into a texture atlas (TexturePacker, free-tex-packer, or Aseprite's own packer): one image means fewer loads and, in WebGL frameworks, fewer draw calls.
- Agree on a tile size (16 or 32 px) and a pivot (feet at the bottom centre) early; changing them later touches every level and sprite.
Test yourself
In a Tiled map, a tile layer contains the gid 2147483714 (0x80000000 + 66). What is it?
- Tile 2147483714
- Tile 66, flipped horizontally
- An empty cell
- Tile 66, rotated 90°
Two tilesets have firstgid 1 and 65. Which tileset and local index does gid 70 refer to?
- First tileset, index 70
- Second tileset, index 5
- Second tileset, index 70
- First tileset, index 69
What does an Aseprite frame tag such as run (from 2 to 4) give your game?
- The file name of the PNG
- The range of frames (and the direction) that make up one named animation
- The colour palette
- The collision box