TypeScript
// Built-in 3x5 pixel font. "#" = ink, rows separated by "/". Lowercase draws as uppercase.
const FONT: Record<string, string> = {
A: "###/#.#/###/#.#/#.#", B: "##./#.#/##./#.#/##.", C: "###/#../#../#../###",
D: "##./#.#/#.#/#.#/##.", E: "###/#../##./#../###", F: "###/#../##./#../#..",
G: "###/#../#.#/#.#/###", H: "#.#/#.#/###/#.#/#.#", I: "###/.#./.#./.#./###",
J: "..#/..#/..#/#.#/###", K: "#.#/#.#/##./#.#/#.#", L: "#../#../#../#../###",
M: "#.#/###/###/#.#/#.#", N: "##./#.#/#.#/#.#/#.#", O: "###/#.#/#.#/#.#/###",
P: "###/#.#/###/#../#..", Q: "###/#.#/#.#/###/..#", R: "##./#.#/##./#.#/#.#",
S: "###/#../###/..#/###", T: "###/.#./.#./.#./.#.", U: "#.#/#.#/#.#/#.#/###",
V: "#.#/#.#/#.#/#.#/.#.", W: "#.#/#.#/###/###/#.#", X: "#.#/#.#/.#./#.#/#.#",
Y: "#.#/#.#/###/.#./.#.", Z: "###/..#/.#./#../###",
"0": "###/#.#/#.#/#.#/###", "1": "##./.#./.#./.#./###", "2": "###/..#/###/#../###",
"3": "###/..#/.##/..#/###", "4": "#.#/#.#/###/..#/..#", "5": "###/#../###/..#/###",
"6": "###/#../###/#.#/###", "7": "###/..#/..#/.#./.#.", "8": "###/#.#/###/#.#/###",
"9": "###/#.#/###/..#/###",
" ": ".../.../.../.../...", ".": "././././#", ",": "../../../.#/#.",
"!": "#/#/#/./#", "?": "###/..#/.##/.../.#.", ":": "./#/./#/.", ";": "../.#/../.#/#.",
"'": "#/#/././.", '"': "#.#/#.#/.../.../...", "-": ".../.../###/.../...",
"+": ".../.#./###/.#./...", "/": "..#/..#/.#./#../#..", "(": ".#/#./#./#./.#",
")": "#./.#/.#/.#/#.", "=": ".../###/.../###/...", "%": "#.#/..#/.#./#../#.#",
"#": "#.#/###/#.#/###/#.#", "*": ".../#.#/.#./#.#/...", _: ".../.../.../.../###",
"<": "..#/.#./#../.#./..#", ">": "#../.#./..#/.#./#..", "&": ".#./#.#/.#./#.#/.##",
"$": ".##/##./.#./.##/##.", "@": "###/#.#/#.#/#../###",
};
const cache = new Map<string, string[]>();
export function glyph(ch: string): string[] {
const k = FONT[ch] ? ch : FONT[ch.toUpperCase()] ? ch.toUpperCase() : "?";
let g = cache.get(k);
if (!g) {
g = FONT[k].split("/");
cache.set(k, g);
}
return g;
}
export interface FontOpts {
scale?: number;
gap?: number;
}
/** Pixel width of a single line. */
export function lineWidth(line: string, opts: FontOpts = {}): number {
const sc = opts.scale ?? 1, gap = opts.gap ?? 1;
let w = 0;
for (const ch of line) w += (glyph(ch)[0].length + gap) * sc;
return line.length ? w - gap * sc : 0;
}
/** Pixel width of the longest line. */
export function textWidth(s: string, opts: FontOpts = {}): number {
return Math.max(0, ...String(s).split("\n").map((l) => lineWidth(l, opts)));
}