Skip to content

Instantly share code, notes, and snippets.

@Alexander-0x80
Forked from alanchrt/triangulate.js
Last active January 5, 2016 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alexander-0x80/91270310116f06069bbf to your computer and use it in GitHub Desktop.
Save Alexander-0x80/91270310116f06069bbf to your computer and use it in GitHub Desktop.
Triangulation of three points and radii
function distance(p1, p2) {
// Find the distance between two points
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
};
function intersect(c1, r1, c2, r2) {
// Find the points of intersection for two circles
// Based on: http://stackoverflow.com/a/3349134
var d = distance(c1, c2);
if (d > r1 + r2) // Circles do not overlap
return [];
if (d < Math.abs(r1 - r2)) // One circle contains the other
return [];
if (d == 0 && r1 == r2) // These are the same circles
return [];
// Find distances of dimensions from the first point
var a = (Math.pow(r1, 2) - Math.pow(r2, 2) + Math.pow(d, 2)) / (2 * d);
var h = Math.sqrt(Math.pow(r1, 2) - Math.pow(a, 2));
// Determine point on the line between centers perpendicular to intersects
var p = point(
c1.x + a * (c2.x - c1.x) / d,
c1.y + a * (c2.y - c1.y) / d
);
// Calculate intersection points
return [
point(
p.x + h * (c2.y - c1.y) / d,
p.y - h * (c2.x - c1.x) / d
),
point(
p.x - h * (c2.y - c1.y) / d,
p.y + h * (c2.x - c1.x) / d
)
];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment