Published
Edited
Sep 11, 2020
1 fork
Importers
8 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function intersect([[x1, y1], [x2, y2]], [[x3, y3], [x4, y4]], sa = false, sb = false ) {
const x1x2 = x1 - x2, y1y2 = y1 - y2,
x1x3 = x1 - x3, y1y3 = y1 - y3,
x3x4 = x3 - x4, y3y4 = y3 - y4;
const d = x1x2 * y3y4 - y1y2 * x3x4;

// parallel or coincident
if (d === 0) return undefined;
const t = (x1x3 * y3y4 - y1y3 * x3x4) / d,
u = -(x1x2 * y1y3 - y1y2 * x1x3) / d;
const ist = t >= 0 && t <= 1,
isu = u >= 0 && u <= 1;
return sa && sb && ist && isu
|| sa && !sb && ist
|| !sa && sb && isu
|| !sa && !sb
? [
x1 + t * (x2 - x1),
y1 + t * (y2 - y1)
]
: undefined;
}
Insert cell
function intersectBox([[x1, y1], [x2, y2]], [b1, b2, b3, b4]) {
const _i1 = intersect([[x1, y1], [x2, y2]], [[b1, b2], [b1, b4]], false, true), // left
_i2 = intersect([[x1, y1], [x2, y2]], [[b1, b2], [b3, b2]], false, true), // top
_i3 = intersect([[x1, y1], [x2, y2]], [[b3, b2], [b3, b4]], false, true), // right
_i4 = intersect([[x1, y1], [x2, y2]], [[b1, b4], [b3, b4]], false, true); // bottom
const dx = x2 - x1;
const dy = y2 - y1;
let i1, i2;
if (_i1) {
if (dx > 0) i1 = _i1;
if (dx < 0) i2 = _i1;
}

if (_i2) {
if (dy > 0) i1 = _i2;
if (dy < 0) i2 = _i2;
}
if (_i3) {
if (dx < 0) i1 = _i3;
if (dx > 0) i2 = _i3;
}
if (_i4) {
if (dy < 0) i1 = _i4;
if (dy > 0) i2 = _i4;
}
return [i1, i2];
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more