UNPKG

@thi.ng/pixel

Version:

Typedarray integer & float pixel buffers w/ customizable formats, blitting, drawing, convolution

82 lines (81 loc) 2.24 kB
import { isNumber } from "@thi.ng/checks/is-number"; import { clamp } from "@thi.ng/math/interval"; const __luminanceABGR = (c) => ((c >>> 16 & 255) * 29 + (c >>> 8 & 255) * 150 + (c & 255) * 76) / 255; const __clampRegion = (sx, sy, w, h, maxw, maxh, dx = 0, dy = 0) => { sx |= 0; sy |= 0; w |= 0; h |= 0; sx < 0 && (w += sx, dx -= sx, sx = 0); sy < 0 && (h += sy, dy -= sy, sy = 0); return [sx, sy, clamp(w, 0, maxw - sx), clamp(h, 0, maxh - sy), dx, dy]; }; const __prepRegions = (src, dest, opts = {}) => { const sw = src.width; const dw = dest.width; let sx, sy; let dx, dy; let rw, rh; [sx, sy, rw, rh] = __clampRegion( opts.sx || 0, opts.sy || 0, opts.w || sw, opts.h || src.height, sw, src.height ); [dx, dy, rw, rh, sx, sy] = __clampRegion( opts.dx || 0, opts.dy || 0, rw, rh, dw, dest.height, sx, sy ); return { sx, sy, dx, dy, rw, rh }; }; const __setChannelUni = (dbuf, src, set) => { for (let i = dbuf.length; i-- > 0; ) { dbuf[i] = set(dbuf[i], src); } }; const __setChannelSame = (dbuf, sbuf, get, set) => { for (let i = dbuf.length; i-- > 0; ) { dbuf[i] = set(dbuf[i], get(sbuf[i])); } }; const __setChannelConvert = (dbuf, sbuf, from, sto, mask) => { const invMask = ~mask; for (let i = dbuf.length; i-- > 0; ) { dbuf[i] = dbuf[i] & invMask | from(sto(sbuf[i])) & mask; } }; const __transformABGR = (pix, format, fn) => { const from = format.fromABGR; const to = format.toABGR; for (let i = pix.length; i-- > 0; ) { pix[i] = from(fn(to(pix[i]))); } }; const __asVec = (x) => isNumber(x) ? [x, x] : x; const __asIntVec = (x) => { const v = __asVec(x); return [v[0] | 0, v[1] | 0]; }; const __swapLane13 = (x) => (x & 255) << 16 | x >> 16 & 255 | x & 4278255360; const __blitCanvas = (buf, canvas, opts = {}) => (canvas instanceof HTMLCanvasElement || canvas instanceof OffscreenCanvas ? canvas.getContext("2d") : canvas).putImageData(buf.toImageData(opts.data), opts.x || 0, opts.y || 0); export { __asIntVec, __asVec, __blitCanvas, __clampRegion, __luminanceABGR, __prepRegions, __setChannelConvert, __setChannelSame, __setChannelUni, __swapLane13, __transformABGR };