UNPKG

@forgesworn/qr

Version:

Dependency-free QR code encoder and decoder for TypeScript, browsers, workers and Node, with optional WebAssembly and tracked camera scanning.

31 lines (30 loc) • 1.26 kB
const BLOCKS = [' ', '▀', '▄', '█']; // none, upper half, lower half, full /** * Renders a code as text, two module rows per line with half-block * characters, one line per row pair and no trailing newline. Needs a * monospace font whose block characters fill the cell. */ export function toTerminal(qr, options = {}) { const margin = options.margin ?? 4; if (!Number.isInteger(margin) || margin < 0) throw new RangeError('Margin must be a whole number of modules'); const inkIsLight = (options.ink ?? 'light') === 'light'; const side = qr.size + margin * 2; const inked = (x, y) => { const mx = x - margin; const my = y - margin; const dark = mx >= 0 && my >= 0 && mx < qr.size && my < qr.size && qr.modules[my * qr.size + mx] === 1; return dark !== inkIsLight; }; const lines = []; for (let y = 0; y < side; y += 2) { let line = ''; for (let x = 0; x < side; x++) { // An odd side leaves the last line's lower half blank (the terminal background). const lower = y + 1 < side && inked(x, y + 1); line += BLOCKS[(inked(x, y) ? 1 : 0) | (lower ? 2 : 0)]; } lines.push(line); } return lines.join('\n'); }