UNPKG

@thi.ng/grid-iterators

Version:

2D grid and shape iterators w/ multiple orderings

32 lines (31 loc) 781 B
import { asInt } from "@thi.ng/api/typedarray"; import { liangBarsky } from "./clipping.js"; function* line(ax, ay, bx, by) { [ax, ay, bx, by] = asInt(ax, ay, bx, by); const dx = Math.abs(bx - ax); const dy = -Math.abs(by - ay); const sx = ax < bx ? 1 : -1; const sy = ay < by ? 1 : -1; let err = dx + dy; while (true) { yield [ax, ay]; if (ax === bx && ay === by) return; let t = err << 1; if (t < dx) { err += dx; ay += sy; } if (t > dy) { err += dy; ax += sx; } } } const lineClipped = (x1, y1, x2, y2, left, top, right, bottom) => { const res = liangBarsky(x1, y1, x2, y2, left, top, right - 1, bottom - 1); return res ? line(res[0], res[1], res[2], res[3]) : void 0; }; export { line, lineClipped };