@thi.ng/rasterize
Version:
Headless 2D shape drawing, filling & rasterization for arbitrary targets/purposes (no canvas required)
45 lines (44 loc) • 1.08 kB
JavaScript
import { isFunction } from "@thi.ng/checks/is-function";
import { isPrimitive } from "@thi.ng/checks/is-primitive";
const __draw2D = (pts, grid, val) => isFunction(val) ? __drawShader2D(pts, grid, val) : __drawSolid2D(pts, grid, val);
const __drawSolid2D = (pts, grid, val) => {
if (!pts) return grid;
if (isPrimitive(val)) {
const {
data,
offset,
stride: [sx, sy]
} = grid;
for (const p of pts) {
data[offset + p[0] * sx + p[1] * sy] = val;
}
} else {
for (const p of pts) {
grid.setAtUnsafe(p[0], p[1], val);
}
}
return grid;
};
const __drawShader2D = (pts, grid, shader) => {
if (!pts) return grid;
if (isPrimitive(grid.getAtUnsafe(0, 0))) {
const {
data,
offset,
stride: [sx, sy]
} = grid;
for (const { 0: x, 1: y } of pts) {
data[offset + x * sx + y * sy] = shader(grid, x, y);
}
} else {
for (const { 0: x, 1: y } of pts) {
grid.setAtUnsafe(x, y, shader(grid, x, y));
}
}
return grid;
};
export {
__draw2D,
__drawShader2D,
__drawSolid2D
};