Skip to content

Sprite Sheet Packer — JavaScript source

Pack loose sprites into one optimized sheet with atlas JSON and CSS — entirely in your browser. Nothing uploads.

This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// sprite-sheet-packer — MaxRects best-short-side-fit sheet packer, plain JS.
// Plain-JavaScript twin of src/lib/sprite-packer.ts: same contract, same
// results, no types and no dependencies — the browser island owns drawing.
export class PackError extends Error {
  constructor(code, message) {
    super(message);
    this.code = code;
  }
}

const MIN_SHEET = 64;
const DEFAULT_CAP = 4096;

/** MaxRects best-short-side-fit packing over a growing power-of-two sheet. */
export function pack(sizes, opts = {}) {
  if (sizes.length === 0) throw new PackError('empty', 'Nothing to pack — add at least one sprite.');

  const seen = new Set();
  for (const s of sizes) {
    if (!Number.isFinite(s.w) || !Number.isFinite(s.h) || s.w <= 0 || s.h <= 0) {
      throw new PackError('invalid', `Sprite "${s.id}" needs positive pixel dimensions.`);
    }
    if (seen.has(s.id)) throw new PackError('invalid', `Duplicate sprite id "${s.id}".`);
    seen.add(s.id);
  }

  const maxWidth = opts.maxWidth ?? DEFAULT_CAP;
  const maxHeight = opts.maxHeight ?? DEFAULT_CAP;

  // Biggest sprites first (max side, then area, then id).
  const order = [...sizes].sort(
    (a, b) =>
      Math.max(b.w, b.h) - Math.max(a.w, a.h) || b.w * b.h - a.w * a.h || (a.id < b.id ? -1 : 1),
  );

  let sheetW = pow2floor(Math.min(MIN_SHEET, maxWidth));
  let sheetH = pow2floor(Math.min(MIN_SHEET, maxHeight));
  for (;;) {
    const attempt = tryPack(order, sheetW, sheetH, opts.allowRotate === true);
    if (Array.isArray(attempt)) return finish(sizes, attempt);

    const nextW = sheetW <= sheetH ? sheetW * 2 : sheetW;
    const nextH = sheetW <= sheetH ? sheetH : sheetH * 2;
    if (nextW > maxWidth || nextH > maxHeight) {
      throw new PackError(
        'overflow',
        `"${attempt}" does not fit within ${maxWidth}×${maxHeight} — split the batch or raise the cap.`,
      );
    }
    sheetW = nextW;
    sheetH = nextH;
  }
}

/** One MaxRects pass over a fixed candidate sheet: all rects, or the first id that failed. */
function tryPack(order, W, H, allowRotate) {
  let free = [{ x: 0, y: 0, w: W, h: H }];
  const placed = [];
  for (const s of order) {
    const best = bestFit(free, s, allowRotate);
    if (!best) return s.id;
    placed.push({ id: s.id, x: best.f.x, y: best.f.y, w: best.w, h: best.h, rotated: best.rotated });
    free = splitFree(free, placed[placed.length - 1]);
  }
  return placed;
}

/** Best short side fit, ties broken by the long side, then by first-seen free rect. */
function bestFit(free, s, allowRotate) {
  let best = null;
  let bestShort = Infinity;
  let bestLong = Infinity;
  const candidates = [{ w: s.w, h: s.h, rotated: false }];
  if (allowRotate && s.w !== s.h) candidates.push({ w: s.h, h: s.w, rotated: true });
  for (const f of free) {
    for (const c of candidates) {
      if (c.w > f.w || c.h > f.h) continue;
      const leftoverW = f.w - c.w;
      const leftoverH = f.h - c.h;
      const short = Math.min(leftoverW, leftoverH);
      const long = Math.max(leftoverW, leftoverH);
      if (short < bestShort || (short === bestShort && long < bestLong)) {
        best = { f, w: c.w, h: c.h, rotated: c.rotated };
        bestShort = short;
        bestLong = long;
      }
    }
  }
  return best;
}

/** MaxRects split: carve the placed rect out of every free rect it touches, then prune contained ones. */
function splitFree(free, p) {
  const next = [];
  for (const f of free) {
    const intersects =
      p.x < f.x + f.w && p.x + p.w > f.x && p.y < f.y + f.h && p.y + p.h > f.y;
    if (!intersects) {
      next.push(f);
      continue;
    }
    if (p.x > f.x) next.push({ x: f.x, y: f.y, w: p.x - f.x, h: f.h });
    if (p.x + p.w < f.x + f.w) next.push({ x: p.x + p.w, y: f.y, w: f.x + f.w - (p.x + p.w), h: f.h });
    if (p.y > f.y) next.push({ x: f.x, y: f.y, w: f.w, h: p.y - f.y });
    if (p.y + p.h < f.y + f.h) next.push({ x: f.x, y: p.y + p.h, w: f.w, h: f.y + f.h - (p.y + p.h) });
  }
  // Prune free rects fully contained in another; the j<i clause keeps exactly
  // one of an identical pair.
  return next.filter((a, i) => !next.some((b, j) => j !== i && contains(b, a) && !(contains(a, b) && j > i)));
}

function contains(outer, inner) {
  return (
    outer.x <= inner.x &&
    outer.y <= inner.y &&
    outer.x + outer.w >= inner.x + inner.w &&
    outer.y + outer.h >= inner.y + inner.h
  );
}

/** Reorder to input order and round the bounding box up to power-of-two sheet dims. */
function finish(sizes, placed) {
  const byId = new Map(placed.map((p) => [p.id, p]));
  let bw = 1;
  let bh = 1;
  for (const p of placed) {
    bw = Math.max(bw, p.x + p.w);
    bh = Math.max(bh, p.y + p.h);
  }
  return {
    sheetW: pow2ceil(bw),
    sheetH: pow2ceil(bh),
    rects: sizes.map((s) => byId.get(s.id)),
  };
}

function pow2ceil(n) {
  let p = 1;
  while (p < n) p *= 2;
  return p;
}

function pow2floor(n) {
  let p = 1;
  while (p * 2 <= n) p *= 2;
  return p;
}

/** Generic JSON atlas: one frame entry per sprite, sheet metadata for engines. */
export function atlasJson(name, r) {
  const frames = {};
  for (const rect of r.rects) {
    frames[rect.id] = { frame: { x: rect.x, y: rect.y, w: rect.w, h: rect.h }, rotated: rect.rotated };
  }
  return JSON.stringify({ frames, meta: { size: { w: r.sheetW, h: r.sheetH }, name } }, null, 2);
}

/** One .sprite-<id> class per rect, positioned against the shared sheet image. */
export function spriteCss(r, sheetName) {
  return r.rects
    .map((rect) =>
      [
        `.sprite-${rect.id} {`,
        `  width: ${rect.w}px;`,
        `  height: ${rect.h}px;`,
        `  background-image: url('${sheetName}');`,
        `  background-position: -${rect.x}px -${rect.y}px;`,
        '}',
      ].join('\n'),
    )
    .join('\n');
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →