javascript get point of line intersection

Solutions on MaxInterview for javascript get point of line intersection by the best coders in the world

showing results for - "javascript get point of line intersection"
Lola
19 Nov 2018
1function line_intersect(x1, y1, x2, y2, x3, y3, x4, y4)
2{
3    var ua, ub, denom = (y4 - y3)*(x2 - x1) - (x4 - x3)*(y2 - y1);
4    if (denom == 0) {
5        return null;
6    }
7    ua = ((x4 - x3)*(y1 - y3) - (y4 - y3)*(x1 - x3))/denom;
8    ub = ((x2 - x1)*(y1 - y3) - (y2 - y1)*(x1 - x3))/denom;
9    return {
10        x: x1 + ua * (x2 - x1),
11        y: y1 + ua * (y2 - y1),
12        seg1: ua >= 0 && ua <= 1,
13        seg2: ub >= 0 && ub <= 1
14    };
15}
Hal
13 Sep 2017
1// line intercept math by Paul Bourke http://paulbourke.net/geometry/pointlineplane/
2// Determine the intersection point of two line segments
3// Return FALSE if the lines don't intersect
4function intersect(x1, y1, x2, y2, x3, y3, x4, y4) {
5
6  // Check if none of the lines are of length 0
7    if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {
8        return false
9    }
10
11    denominator = ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1))
12
13  // Lines are parallel
14    if (denominator === 0) {
15        return false
16    }
17
18    let ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator
19    let ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator
20
21  // is the intersection along the segments
22    if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
23        return false
24    }
25
26  // Return a object with the x and y coordinates of the intersection
27    let x = x1 + ua * (x2 - x1)
28    let y = y1 + ua * (y2 - y1)
29
30    return {x, y}
31}
32