Drawing a map from JSON and sprites, step by step
The server PNG is convenient, but you can draw any map yourself from its JSON and the free art pack: at any of the four angles, any scale, live in a browser or VTT, with no per-image cost. The two programs on this page use the same algorithm as the server renderer. Both were checked against real server renders: the Python version produced pixel-identical images (iso0 at 0.25, iso90 and iso270 at 0.5), and the browser version matched to within ±2 colour levels from canvas smoothing.
Download them: draw-map.js and draw_map.py.
Step 1: get the map and the pack
Generate or fetch the map on your server (the key must stay secret; see API keys), then hand the JSON to the client. The pack is public, so the client loads it directly from the version named in map.pack. See Art packs for the files.
Step 2: the isometric projection
A map point (gx, gy) in cells (x east, y south) becomes a screen point in pixels at full scale:
[s, c] = SIGN[angle] iso0: [1, 1] iso90: [1, -1] iso180: [-1, -1] iso270: [-1, 1]
screenX = 128 * (gx * c + gy * s)
screenY = -64 * (gx * s - gy * c)
depth = -(gx * s - gy * c) bigger = nearer the camera
A floor cell becomes a diamond 256 px wide and 128 px tall. For iso0, cell (0, 0)’s centre (0.5, 0.5) lands at (128, 0) and cell (1, 0)’s at (256, -64): one cell east moves 128 px right and 64 px up. At smaller scales multiply the result by the scale (0.5 or 0.25).
Step 3: footprint boxes and anchors
Every piece gets a box [x0, y0, x1, y1] in cells. Its sprite’s anchor is drawn at the projected box centre.
| Piece | Box | Rotation used for the sprite |
|---|---|---|
| Floor at cell (x, y) | [x, y, x+1, y+1] |
floorRot |
| Horizontal edge (wall or door) at line y, x to x+1 | [x+T, y−T, x+1−T, y+T] |
0 |
| Vertical edge at line x, y to y+1 | [x−T, y+T, x+T, y+1−T] |
1 |
| Vertex (wall post) at point (x, y) | [x−T, y−T, x+T, y+T] |
vertexRot |
Prop at at = [x, y], footprint [w, d] (swap on odd rot) |
[x+T, y+T, x+w−T, y+d−T] |
rot |
T = 0.1 cell is half the wall thickness. The sprite for a piece with rotation r seen from angle is the one rendered for FACINGS[(index(angle) − r) mod 4]. That is how one set of four renders covers every rotation.
To place a frame: left = screenX * scale − frame.ax, top = screenY * scale − frame.ay. Frame sizes and anchors at full scale: floor 256 × 176 at (128, 64); wall segment, portal and prop 256 × 512 at (128, 448); vertex 64 × 512 at (32, 480). Multi-cell props are bigger (Art packs).
Step 4: wall modes
full: every wall at full height.cutaway(short walls, the default for the API and the examples below): every full-height wall segment is swapped for its 3 ft cutaway version (wall.seg.full.*→wall.seg.cut.*) so you can see into every room.auto: only walls with floor behind them from the camera’s point of view are lowered, so the near walls don’t hide rooms while the far walls stay tall.- A wall post (vertex) uses the full version only if one of its four neighbouring edges is still full height or a door; otherwise it becomes the
.cutpost. - Doors and other portals always stay full height. That includes secret doors (
portal.secret.closed), which is what a game master wants: every secret door stands out. - For a player handout, draw each secret door as plain wall (
wall.seg.full.a) before applying the wall mode, and leave out everything the players can’t reach from the entrance without passing a secret door. The server does this for you withsecrets=hideon the PNG endpoint (Endpoints).
Step 5: draw order
- Floors first, sorted by depth (far to near), ties broken by screen x, then by the order they were added.
- Everything standing (walls, posts, doors, props) in topological order: if two pieces’ screen rectangles overlap and one is entirely behind the other along a grid axis, the one behind is drawn first. Screen rectangles are the projected box raised by the tallest piece’s height (≈334 px at full scale) so tall walls are compared correctly. Pieces with no ordering between them fall back to the floor ordering.
Simple depth sorting alone puts long walls in front of props they should hide; the topological step is what makes the result match the server.
Step 6: canvas and blit
Take the bounding box of every frame placed at its anchor, add 8 px of padding on each side, fill with parchment rgb(239, 230, 210) (or leave transparent), and draw each frame in order with its top-left rounded to whole pixels.
Full JavaScript (browser canvas)
// Draw an IsoDelve map (isodelve-map@1) on a <canvas> from its JSON and the public art pack.
// Usage: const canvas = await drawMap(mapJson, { angle: "iso0", scale: 0.25, walls: "cutaway" });
// Pack files are public (CORS *), so the browser needs no key. Fetch the map JSON through your own server.
const API = "https://api.isodelve.com";
const FACINGS = ["iso0", "iso90", "iso180", "iso270"];
const SIGN = { iso0: [1, 1], iso90: [1, -1], iso180: [-1, -1], iso270: [-1, 1] }; // signs of sin, cos of the view bearing
const T = 0.1; // half wall thickness, in cells
const LIFT = (3.048 + 0.2) * Math.cos(Math.PI / 6) * 256 / (1.524 * Math.SQRT2); // tallest piece, px at scale 1
export async function drawMap(map, { angle = "iso0", scale = 0.25, walls = "cutaway", api = API } = {}) {
if (map.format !== "isodelve-map@1") throw new Error(`unsupported format ${map.format}`);
const [packId, version] = map.pack.split("@");
const base = `${api}/v1/packs/${packId}/${version}/`;
const manifest = await (await fetch(base + "manifest.json")).json();
const footprint = Object.fromEntries(manifest.pieces.map((p) => [p.id, p.footprint ?? [1, 1]]));
const sprites = {}; // "piece|facing" -> frame + image
await Promise.all(manifest.atlases.filter((a) => a.scale === scale).map(async (ref) => {
const data = await (await fetch(base + ref.data)).json();
const img = new Image(); img.crossOrigin = "anonymous"; img.src = base + ref.image; await img.decode();
for (const fr of data.frames) sprites[`${fr.id}|${ref.facing}`] = { img, ...fr };
}));
const [s, c] = SIGN[angle];
const project = (gx, gy) => [128 * (gx * c + gy * s), -64 * (gx * s - gy * c)]; // grid -> px at scale 1
const depth = (gx, gy) => -(gx * s - gy * c); // bigger = nearer
const spriteFacing = (rot) => FACINGS[(((FACINGS.indexOf(angle) - rot) % 4) + 4) % 4];
// 1. Wall mode: lower wall segments that stand in front of floor (auto) or all of them (cutaway).
const g = map.grid, W = g.w, H = g.h, P = g.palette;
const floorAt = (x, y) => x >= 0 && y >= 0 && x < W && y < H && g.floor[y * W + x] !== 0;
const low = (id, behindIsFloor) => !id || !id.startsWith("wall.seg.full.") || walls === "full" || (walls === "auto" && !behindIsFloor) ? id : id.replace("wall.seg.full.", "wall.seg.cut.");
const eh = g.edgeH.map((v, k) => low(P[v], floorAt(k % W, c > 0 ? Math.floor(k / W) - 1 : Math.floor(k / W))));
const ev = g.edgeV.map((v, k) => low(P[v], floorAt(s > 0 ? k % (W + 1) : (k % (W + 1)) - 1, Math.floor(k / (W + 1)))));
const full = (id) => !!id && (id.startsWith("portal.") || id.includes(".full."));
// 2. Every piece stands on a box [x0, y0, x1, y1] in cells; its sprite anchor goes at the box centre.
const items = [];
const add = (id, rot, box, layer) => {
if (!id) return;
const gx = (box[0] + box[2]) / 2, gy = (box[1] + box[3]) / 2, [px, py] = project(gx, gy);
items.push({ id, facing: spriteFacing(rot), px, py, box, layer, key: depth(gx, gy), order: items.length });
};
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) add(P[g.floor[y * W + x]], g.floorRot[y * W + x], [x, y, x + 1, y + 1], 0);
for (let y = 0; y <= H; y++) for (let x = 0; x < W; x++) add(eh[y * W + x], 0, [x + T, y - T, x + 1 - T, y + T], 1);
for (let y = 0; y < H; y++) for (let x = 0; x <= W; x++) add(ev[y * (W + 1) + x], 1, [x - T, y + T, x + T, y + 1 - T], 1);
for (let y = 0; y <= H; y++) for (let x = 0; x <= W; x++) {
let id = P[g.vertex[y * (W + 1) + x]]; if (!id) continue; // posts follow their tallest wall
const near = [y > 0 && ev[(y - 1) * (W + 1) + x], y < H && ev[y * (W + 1) + x], x < W && eh[y * W + x], x > 0 && eh[y * W + x - 1]];
if (!near.some(full)) id = id.replace(/\.full$/, ".cut");
add(id, g.vertexRot[y * (W + 1) + x], [x - T, y - T, x + T, y + T], 1);
}
for (const p of map.props) { // at = NW cell; dims swap on odd rot
const [w, d] = footprint[p.piece] ?? [1, 1], [dx, dy] = p.rot % 2 ? [d, w] : [w, d], [x, y] = p.at;
add(p.piece, p.rot, [x + T, y + T, x + dx - T, y + dy - T], 1);
}
// 3. Draw order: floors by depth, then standing pieces topologically (behind-on-a-grid-axis first).
const cmp = (a, b) => a.key - b.key || a.px - b.px || a.order - b.order;
const order = [...items.filter((i) => !i.layer).sort(cmp), ...topo(items.filter((i) => i.layer))];
function topo(list) {
const behind = (a, b) => (s > 0 ? a.box[0] >= b.box[2] : a.box[2] <= b.box[0]) || (c > 0 ? a.box[3] <= b.box[1] : a.box[1] >= b.box[3]);
const R = list.map((it) => { const p = [[0, 1], [2, 1], [0, 3], [2, 3]].map(([i, j]) => project(it.box[i], it.box[j]));
return [Math.min(...p.map((q) => q[0])), Math.min(...p.map((q) => q[1])) - LIFT, Math.max(...p.map((q) => q[0])), Math.max(...p.map((q) => q[1]))]; });
const n = list.length, succ = list.map(() => []), indeg = new Array(n).fill(0);
const byX = [...list.keys()].sort((a, b) => R[a][0] - R[b][0]);
for (let u = 0; u < n; u++) for (let v = u + 1; v < n; v++) {
const i = byX[u], j = byX[v]; if (R[j][0] >= R[i][2]) break;
if (R[j][1] >= R[i][3] || R[i][1] >= R[j][3]) continue;
const ij = behind(list[i], list[j]), ji = behind(list[j], list[i]);
if (ij && !ji) { succ[i].push(j); indeg[j]++; } else if (ji && !ij) { succ[j].push(i); indeg[i]++; }
}
const byCmp = (a, b) => cmp(list[a], list[b]);
let ready = [...list.keys()].filter((i) => !indeg[i]).sort(byCmp); const out = [], done = new Array(n).fill(false);
while (out.length < n) {
if (!ready.length) ready = [[...list.keys()].filter((i) => !done[i]).sort(byCmp)[0]]; // cycle guard (never seen)
const i = ready.shift(); if (done[i]) continue;
done[i] = true; out.push(list[i]);
for (const j of succ[i]) if (--indeg[j] === 0 && !done[j]) { ready.push(j); ready.sort(byCmp); }
}
return out;
}
// 4. Canvas = bounds of every sprite frame at its anchor, plus 8 px padding; then blit in order.
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
for (const it of order) { const sp = sprites[`${it.id}|${it.facing}`];
if (!sp) throw new Error(`pack ${map.pack} has no sprite ${it.id} at ${it.facing}`);
const l = it.px * scale - sp.ax, t = it.py * scale - sp.ay;
x0 = Math.min(x0, l); y0 = Math.min(y0, t); x1 = Math.max(x1, l + sp.w); y1 = Math.max(y1, t + sp.h); }
const pad = 8, canvas = document.createElement("canvas");
canvas.width = Math.round(x1 - x0 + 2 * pad); canvas.height = Math.round(y1 - y0 + 2 * pad);
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(239,230,210)"; ctx.fillRect(0, 0, canvas.width, canvas.height); // parchment; skip for transparent
for (const it of order) { const sp = sprites[`${it.id}|${it.facing}`];
ctx.drawImage(sp.img, sp.x, sp.y, sp.w, sp.h, Math.round(pad - x0 + it.px * scale - sp.ax), Math.round(pad - y0 + it.py * scale - sp.ay), sp.w, sp.h); }
return canvas;
}
Use it:
<script type="module">
import { drawMap } from "/guide/files/draw-map.js";
const map = await (await fetch("/my-server/map.json")).json(); // your server fetched it with the key
const canvas = await drawMap(map, { angle: "iso0", scale: 0.5, walls: "cutaway" });
document.body.append(canvas);
// canvas.toBlob((b) => …) gives you a PNG to download
</script>
Full Python (Pillow)
"""Draw an IsoDelve map (isodelve-map@1) from its JSON and the public art pack.
pip install pillow
python draw_map.py map.json out.png --angle iso0 --scale 0.25 --walls cutaway
Pack files are public, so no API key is needed here. Get map.json from your own
server (POST /v1/maps with your key) and keep the key out of client code.
"""
import argparse, io, json, math, urllib.request
from functools import cmp_to_key
from PIL import Image
FACINGS = ["iso0", "iso90", "iso180", "iso270"]
SIGN = {"iso0": (1, 1), "iso90": (1, -1), "iso180": (-1, -1), "iso270": (-1, 1)} # signs of sin, cos of the view bearing
T = 0.1 # half wall thickness, in cells
LIFT = (3.048 + 0.2) * math.cos(math.radians(30)) * 256 / (1.524 * math.sqrt(2)) # tallest piece, in px at scale 1
UA = {"User-Agent": "isodelve-guide-example"}
def get(url):
with urllib.request.urlopen(urllib.request.Request(url, headers=UA)) as r:
return r.read()
def project(f, gx, gy):
"""Grid point (gx east, gy south, in cells) -> screen px at scale 1."""
s, c = SIGN[f]
return 128 * (gx * c + gy * s), -64 * (gx * s - gy * c)
def depth(f, gx, gy):
s, c = SIGN[f]
return -(gx * s - gy * c) # bigger = nearer the camera
def sprite_facing(f, rot):
return FACINGS[(FACINGS.index(f) - rot) % 4]
def apply_walls(m, f, mode):
"""walls=auto lowers wall segments standing in front of floor; cutaway lowers them all."""
g = m["grid"]; W, H = g["w"], g["h"]; s, c = SIGN[f]; pal = g["palette"]
floor_at = lambda x, y: 0 <= x < W and 0 <= y < H and g["floor"][y * W + x] != 0
def low(pid, behind_is_floor):
if not pid or not pid.startswith("wall.seg.full.") or mode == "full" or (mode == "auto" and not behind_is_floor):
return pid
return pid.replace("wall.seg.full.", "wall.seg.cut.")
eh = [low(pal[v], floor_at(k % W, k // W - 1 if c > 0 else k // W)) for k, v in enumerate(g["edgeH"])]
ev = [low(pal[v], floor_at(k % (W + 1) if s > 0 else k % (W + 1) - 1, k // (W + 1))) for k, v in enumerate(g["edgeV"])]
full = lambda pid: bool(pid) and (pid.startswith("portal.") or ".full." in pid)
vx = []
for k, v in enumerate(g["vertex"]):
pid = pal[v]; x, y = k % (W + 1), k // (W + 1)
if pid:
near = [ev[(y - 1) * (W + 1) + x] if y > 0 else "", ev[y * (W + 1) + x] if y < H else "",
eh[y * W + x] if x < W else "", eh[y * W + x - 1] if x > 0 else ""]
if not any(full(n) for n in near):
pid = pid[:-5] + ".cut" if pid.endswith(".full") else pid
vx.append(pid)
return eh, ev, vx
def draw_list(m, f, mode, footprints):
g = m["grid"]; W, H = g["w"], g["h"]; pal = g["palette"]
eh, ev, vx = apply_walls(m, f, mode)
items = []
def add(pid, rot, box, layer):
if not pid: return
gx, gy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2
px, py = project(f, gx, gy)
items.append(dict(id=pid, facing=sprite_facing(f, rot), px=px, py=py, box=box, layer=layer, key=depth(f, gx, gy), order=len(items)))
for y in range(H):
for x in range(W):
add(pal[g["floor"][y * W + x]], g["floorRot"][y * W + x], (x, y, x + 1, y + 1), 0)
for y in range(H + 1):
for x in range(W):
add(eh[y * W + x], 0, (x + T, y - T, x + 1 - T, y + T), 1)
for y in range(H):
for x in range(W + 1):
add(ev[y * (W + 1) + x], 1, (x - T, y + T, x + T, y + 1 - T), 1)
for y in range(H + 1):
for x in range(W + 1):
add(vx[y * (W + 1) + x], g["vertexRot"][y * (W + 1) + x], (x - T, y - T, x + T, y + T), 1)
for p in m["props"]: # at = north-west cell of the footprint; dims swap on odd rot
w, d = footprints.get(p["piece"], (1, 1)); dx, dy = (d, w) if p["rot"] % 2 else (w, d); x, y = p["at"]
add(p["piece"], p["rot"], (x + T, y + T, x + dx - T, y + dy - T), 1)
cmp = lambda a, b: (a["key"] > b["key"]) - (a["key"] < b["key"]) or (a["px"] > b["px"]) - (a["px"] < b["px"]) or a["order"] - b["order"]
floors = sorted([i for i in items if i["layer"] == 0], key=cmp_to_key(cmp))
return floors + topo(f, [i for i in items if i["layer"] == 1], cmp)
def topo(f, items, cmp):
"""Standing pieces: draw each after every screen-overlapping piece wholly behind it on a grid axis."""
s, c = SIGN[f]
def behind(a, b):
a, b = a["box"], b["box"]
east = a[0] >= b[2] if s > 0 else a[2] <= b[0]
south = a[3] <= b[1] if c > 0 else a[1] >= b[3]
return east or south
def rect(it):
pts = [project(f, it["box"][i], it["box"][j]) for i in (0, 2) for j in (1, 3)]
xs, ys = [p[0] for p in pts], [p[1] for p in pts]
return min(xs), min(ys) - LIFT, max(xs), max(ys)
R = [rect(i) for i in items]; n = len(items)
succ = [[] for _ in items]; indeg = [0] * n
by_x = sorted(range(n), key=lambda i: R[i][0])
for u, i in enumerate(by_x):
for j in by_x[u + 1:]:
if R[j][0] >= R[i][2]: break
if R[j][1] >= R[i][3] or R[i][1] >= R[j][3]: continue
ij, ji = behind(items[i], items[j]), behind(items[j], items[i])
if ij and not ji: succ[i].append(j); indeg[j] += 1
elif ji and not ij: succ[j].append(i); indeg[i] += 1
key = cmp_to_key(lambda a, b: cmp(items[a], items[b]))
ready = sorted([i for i in range(n) if indeg[i] == 0], key=key); out = []; done = [False] * n
while len(out) < n:
if not ready: # a cycle (never seen): release the shallowest remaining piece
ready = [min((i for i in range(n) if not done[i]), key=key)]
i = ready.pop(0)
if done[i]: continue
done[i] = True; out.append(items[i])
for j in succ[i]:
indeg[j] -= 1
if indeg[j] == 0 and not done[j]:
ready.append(j); ready.sort(key=key)
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("map"); ap.add_argument("out")
ap.add_argument("--angle", default="iso0", choices=FACINGS)
ap.add_argument("--scale", type=float, default=0.25, choices=[1, 0.5, 0.25])
ap.add_argument("--walls", default="cutaway", choices=["full", "cutaway", "auto"])
ap.add_argument("--api", default="https://api.isodelve.com")
a = ap.parse_args()
m = json.load(open(a.map))
assert m["format"] == "isodelve-map@1", m["format"]
pack_id, version = m["pack"].split("@")
base = f"{a.api}/v1/packs/{pack_id}/{version}/"
manifest = json.loads(get(base + "manifest.json"))
footprints = {p["id"]: tuple(p.get("footprint", (1, 1))) for p in manifest["pieces"]}
sprites = {} # (piece, facing) -> cropped RGBA sprite + anchor
for ref in manifest["atlases"]:
if ref["scale"] != a.scale: continue
data = json.loads(get(base + ref["data"]))
sheet = Image.open(io.BytesIO(get(base + ref["image"]))).convert("RGBA")
for fr in data["frames"]:
sprites[(fr["id"], ref["facing"])] = (sheet.crop((fr["x"], fr["y"], fr["x"] + fr["w"], fr["y"] + fr["h"])), fr["ax"], fr["ay"])
items = draw_list(m, a.angle, a.walls, footprints)
# Canvas = bounds of every sprite frame placed at its anchor, plus 8 px padding.
boxes = []
for it in items:
img, ax, ay = sprites[(it["id"], it["facing"])]
left, top = it["px"] * a.scale - ax, it["py"] * a.scale - ay
boxes.append((left, top, left + img.width, top + img.height))
x0, y0 = min(b[0] for b in boxes), min(b[1] for b in boxes)
x1, y1 = max(b[2] for b in boxes), max(b[3] for b in boxes)
pad = 8; ox, oy = -x0 + pad, -y0 + pad
out = Image.new("RGBA", (round(x1 - x0 + 2 * pad), round(y1 - y0 + 2 * pad)), (239, 230, 210, 255)) # parchment
for it in items:
img, ax, ay = sprites[(it["id"], it["facing"])]
out.alpha_composite(img, (round(ox + it["px"] * a.scale - ax), round(oy + it["py"] * a.scale - ay)))
out.save(a.out)
print(f"{a.out}: {out.width}x{out.height}, {len(items)} sprites, {m['id']} {a.angle} scale {a.scale} walls {a.walls}")
if __name__ == "__main__":
main()
Run it:
pip install pillow
curl -s -H "Authorization: Bearer $ISODELVE_KEY" -o map.json \
https://api.isodelve.com/v1/maps/map_1t2nde66019682yc.json
python draw_map.py map.json map-iso90.png --angle iso90 --scale 0.5
Turning the map
Turning is just drawing again with the next angle: iso0 → iso90 → iso180 → iso270. Cache the atlases for every angle you offer and keep the map JSON; nothing else changes. For a VTT, keep the same cell grid underneath, because the projection maps cells to the screen the same way for tokens.
Next: Rate limits and errors.