Skip to content

Bitmap Font Generator — JavaScript source

Turn a TTF into a game-ready bitmap font sheet + BMFont .fnt — entirely in your browser. Nothing uploads.

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

// bitmap-font-generator — charset parser + BMFont TEXT emitter, plain JS.
// Plain-JavaScript twin of src/lib/bitmap-font.ts: same charset grammar
// (presets, decimal and U+HEX ranges) and same BMFont TEXT output, no types
// and no dependencies — rasterizing stays in the browser island.
export class FontError extends Error {
  constructor(message) {
    super(message);
    this.code = 'invalid';
  }
}

/** Max valid Unicode scalar value. */
const MAX_CODEPOINT = 0x10ffff;

/** Inclusive [lo, hi] codepoint range expanded to a sorted list. */
function range(lo, hi) {
  const out = [];
  for (let cp = lo; cp <= hi; cp++) out.push(cp);
  return out;
}

/** Named charsets, as documented in the tool docs. */
const PRESETS = {
  ascii: range(32, 126),
  latin1: [...range(32, 126), ...range(160, 255)],
  digits: range(48, 57),
};

/** Parse a charset spec into a deduped, sorted codepoint list. */
export function parseCharset(spec) {
  const trimmed = spec.trim();
  if (trimmed === '') throw new FontError('Charset is empty — name a preset or list codepoint ranges.');
  const preset = PRESETS[trimmed.toLowerCase()];
  if (preset) return [...preset];

  const seen = new Set();
  for (const raw of trimmed.split(',')) {
    const token = raw.trim().replace(/\s+/g, '');
    const bounds = parseToken(token);
    for (let cp = bounds.lo; cp <= bounds.hi; cp++) seen.add(cp);
  }
  return [...seen].sort((a, b) => a - b);
}

/** One comma item → inclusive bounds, or FontError when garbage. */
function parseToken(token) {
  // Hex form: U+HEX or U+HEX-HEX (end may drop the U+ prefix).
  const hex = /^u\+([0-9a-f]+)(?:-([0-9a-f]+))?$/i.exec(token);
  // Decimal form: N or N-N.
  const dec = /^(\d+)(?:-(\d+))?$/.exec(token);
  if (!hex && !dec) {
    throw new FontError(`"${token}" is not a codepoint or range — use 65-90 or U+4E00-9FFF.`);
  }
  const radix = hex ? 16 : 10;
  const [, loRaw, hiRaw] = hex ?? dec;
  const lo = Number.parseInt(loRaw, radix);
  const hi = hiRaw !== undefined ? Number.parseInt(hiRaw, radix) : lo;
  if (lo > MAX_CODEPOINT || hi > MAX_CODEPOINT) {
    throw new FontError(`"${token}" is outside Unicode (max U+10FFFF).`);
  }
  if (lo > hi) throw new FontError(`"${token}" runs backwards — put the smaller codepoint first.`);
  return { lo, hi };
}

/** Emit a BMFont TEXT-format document; pages are always 1 (`sheet.png`). */
export function fntText(info, common, chars, kernings) {
  const p = info.padding;
  const lines = [
    `info face="${info.face}" size=${info.size} bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=${p},${p},${p},${p} spacing=1,1 outline=0`,
    `common lineHeight=${common.lineHeight} base=${common.base} scaleW=${common.scaleW} scaleH=${common.scaleH} pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0`,
    'page id=0 file="sheet.png"',
    `chars count=${chars.length}`,
    ...chars.map(
      (c) =>
        `char id=${c.codepoint} x=${c.x} y=${c.y} width=${c.w} height=${c.h} xoffset=${c.xoffset} yoffset=${c.yoffset} xadvance=${c.xadvance} page=0 chnl=15`,
    ),
    `kernings count=${kernings.length}`,
    ...kernings.map((k) => `kerning first=${k.first} second=${k.second} amount=${k.amount}`),
  ];
  return lines.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 →