UNPKG

@thi.ng/rasterize

Version:

Headless 2D shape drawing, filling & rasterization for arbitrary targets/purposes (no canvas required)

45 lines (44 loc) 1.41 kB
import { isFunction } from "@thi.ng/checks/is-function"; import { porterDuffP, porterDuffPInt, SRC_OVER_F, SRC_OVER_I } from "@thi.ng/porter-duff/porter-duff"; import { SYSTEM } from "@thi.ng/random/system"; const defPattern = (pattern) => { const [w, h] = pattern.size; return (_, x, y) => pattern.getAtUnsafe(x % w, y % h); }; const defStripes = ({ dir, size, sizeA, a, b }) => dir === "h" ? (_, x) => x % size < sizeA ? a : b : dir === "v" ? (_, __, y) => y % size < sizeA ? a : b : (_, x, y) => (x + y) % size < sizeA ? a : b; const defNoise = (opts) => { const { probability = 0.5, rnd = SYSTEM, a, b } = opts; return () => rnd.probability(probability) ? a : b; }; const defBlendF = (col, blend = SRC_OVER_F, isPremultiplied = false) => { blend = isPremultiplied ? blend : porterDuffP(blend); return isFunction(col) ? (buf, x, y) => { const dest = buf.getAtUnsafe(x, y); return blend(dest, col(buf, x, y), dest); } : (buf, x, y) => { const dest = buf.getAtUnsafe(x, y); return blend(dest, col, dest); }; }; const defBlendI = (col, blend = SRC_OVER_I, isPremultiplied = false) => { blend = isPremultiplied ? blend : porterDuffPInt(blend); return isFunction(col) ? (buf, x, y) => blend(col(buf, x, y), buf.getAtUnsafe(x, y)) : (buf, x, y) => blend(col, buf.getAtUnsafe(x, y)); }; export { defBlendF, defBlendI, defNoise, defPattern, defStripes };