UNPKG

@thi.ng/text-canvas

Version:

Text based canvas, drawing, plotting, tables with arbitrary formatting (incl. ANSI/HTML)

72 lines (71 loc) 1.78 kB
import { peek } from "@thi.ng/arrays/peek"; import { NONE } from "@thi.ng/text-format/api"; import { hline, vline } from "./hvline.js"; import { charCode } from "./utils.js"; const clear = (canvas, reset = false, code = 32) => { const rects = canvas.clipRects; if (reset) { rects.length = canvas.styles.length = 1; canvas.format = canvas.defaultFormat; } code = charCode(code, canvas.format); if (rects.length > 1) { const { x1, y1, w, h } = peek(rects); fillRect(canvas, x1, y1, w, h, code); } else { canvas.data.fill(code); } }; const clearFormat = ({ data }, format = NONE) => { format <<= 16; for (let i = data.length; i-- > 0; ) data[i] = data[i] & 65535 | format; }; const fillRect = (canvas, x, y, w, h, char, format = canvas.format) => { x |= 0; y |= 0; w |= 0; h |= 0; const { x1, y1, x2, y2 } = peek(canvas.clipRects); if (x < x1) { w += x - x1; x = x1; } if (y < y1) { h += y - y1; y = y1; } const { data, width } = canvas; if (w < 1 || h < 1 || x >= x2 || y >= y2) return; w = Math.min(w, x2 - x); h = Math.min(h, y2 - y); char = charCode(char, format); for (; h-- > 0; y++) { const idx = x + y * width; data.fill(char, idx, idx + w); } }; const strokeRect = (canvas, x, y, w, h, format = canvas.format) => { w |= 0; h |= 0; if (w < 2 || h < 2) return; const style = peek(canvas.styles); hline(canvas, x, y, w, style.tl, style.tr, style.hl, format); hline(canvas, x, y + h - 1, w, style.bl, style.br, style.hl, format); vline(canvas, x, y + 1, h - 2, void 0, void 0, void 0, format); vline( canvas, x + w - 1, y + 1, h - 2, void 0, void 0, void 0, format ); }; export { clear, clearFormat, fillRect, strokeRect };