Public
Edited
Jul 19, 2024
Insert cell
Insert cell
Insert cell
Insert cell
function polygonIncircle(points) {
let circle = [NaN, NaN, 0];
for (var i = 0, n = points.length; i < n; ++i) {
const pi0 = points[i], pi1 = points[(i + 1) % n];
for (let j = i + 1; j < n; ++j) {
const pj0 = points[j], pj1 = points[(j + 1) % n];
const pij = j === i + 1 ? pj0 : lineLineIntersection(pi0, pi1, pj0, pj1);
search: for (let k = j + 1; k < n; ++k) {
const pk0 = points[k], pk1 = points[(k + 1) % n];
const pik = lineLineIntersection(pi0, pi1, pk0, pk1);
const pjk = k === j + 1 ? pk0 : lineLineIntersection(pj0, pj1, pk0, pk1);
const c = triangleIncircle(pij, pik, pjk);
for (let l = 0; l < n; ++l) {
const pl0 = points[l];
const pl1 = points[(l + 1) % n];
const r = pointLineDistance(c, pl0, pl1);
if (r < circle[2]) continue search;
if (r < c[2]) c[2] = r;
}
circle = c;
}
}
}
return circle;
}
Insert cell
Insert cell
function triangleIncircle(p0, p1, p2) {
const [x0, y0] = p0, [x1, y1] = p1, [x2, y2] = p2;
const x01 = x0 - x1, y01 = y0 - y1;
const x02 = x0 - x2, y02 = y0 - y2;
const x12 = x1 - x2, y12 = y1 - y2;
const l01 = Math.sqrt(x01 * x01 + y01 * y01);
const l02 = Math.sqrt(x02 * x02 + y02 * y02);
const l12 = Math.sqrt(x12 * x12 + y12 * y12);
const k0 = l01 / (l01 + l02);
const k1 = l12 / (l12 + l01);
const c = lineLineIntersection(p0, [x1 - k0 * x12, y1 - k0 * y12], p1, [x2 + k1 * x02, y2 + k1 * y02]);
c[2] = Math.sqrt((l02 + l12 - l01) * (l12 + l01 - l02) * (l01 + l02 - l12) / (l01 + l02 + l12)) / 2;
return c;
}
Insert cell
Insert cell
function pointLineDistance([x0, y0], [x1, y1], [x2, y2]) {
const x21 = x2 - x1, y21 = y2 - y1;
return (y21 * x0 - x21 * y0 + x2 * y1 - y2 * x1) / Math.sqrt(y21 * y21 + x21 * x21);
}
Insert cell
Insert cell
function lineLineIntersection([x0, y0], [x1, y1], [x2, y2], [x3, y3]) {
const x02 = x0 - x2, y02 = y0 - y2;
const x10 = x1 - x0, y10 = y1 - y0;
const x32 = x3 - x2, y32 = y3 - y2;
const t = (x32 * y02 - y32 * x02) / (y32 * x10 - x32 * y10);
return [x0 + t * x10, y0 + t * y10];
}
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more