Skip to content

Instantly share code, notes, and snippets.

@bohnacker
Last active May 5, 2019 09:18
Show Gist options
  • Save bohnacker/d251f1ba478c6bee4575f2f0f95de8e1 to your computer and use it in GitHub Desktop.
Save bohnacker/d251f1ba478c6bee4575f2f0f95de8e1 to your computer and use it in GitHub Desktop.
Checks if two lines are crossing and returns the crossing point. There are two modes: if infinite is false, there will be a result only if the lines are crossing between their start and end points. Otherwise the lines will be thought of being infinite.
// Checks, if two lines (p1a to p1b) and (p2a to p2b) are crossing.
// Points are given as [x, y]. If inifinte1 is true, the first line
// will be continued before start and after end points. Same for line 2.
// Returns the crossing point as [x, y] or false if there is none.
// ATTENTION: this calculation is not completely precice in some cases!
function crossingPoint(p1a, p1b, p2a, p2b, infinite1, infinite2) {
// vectors from start to end points
let d1x = p1b[0] - p1a[0];
let d1y = p1b[1] - p1a[1];
let d2x = p2b[0] - p2a[0];
let d2y = p2b[1] - p2a[1];
// both lines horizontal or vertical
if (d1x == 0 && d2x == 0) return false;
if (d1y == 0 && d2y == 0) return false;
if (d1y == 0) d1y = 0.000001;
let gdiv = d2x - d2y * d1x / d1y;
if (gdiv == 0) gdiv = 0.000001;
let g = (p1a[0] - p2a[0] + p2a[1] * d1x / d1y - p1a[1] * d1x / d1y) / gdiv;
if (!infinite2 && (g < 0 || g > 1)) return false;
if (infinite1) return [p2a[0] + d2x * g, p2a[1] + d2y * g];
let f = p2a[1] / d1y - p1a[1] / d1y + g * d2y / d1y;
if (!infinite1 && (f < 0 || f > 1)) return false;
return [p1a[0] + d1x * f, p1a[1] + d1y * f];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment