EN
TypeScript - calculate intersection point of two lines for given 4 points
0
points
Intersection point formula for given two points on each line should be calculated in the following way:
Where:
L1andL2represent points on line 1 and line 2 calculated with linear parametric equation. Points(x1, y1)and(x2, y2)are located on line 1,(x3, y3)and(x4, y4)are located on line 2.
Practical example
Using TypeScript it is possible to calculate intersection points using the above formula in the following way:
const calculateIntersection = (
p1: Point,
p2: Point,
p3: Point,
p4: Point
): Point => {
// down part of intersection point formula
const d1 = (p1.x - p2.x) * (p3.y - p4.y); // (x1 - x2) * (y3 - y4)
const d2 = (p1.y - p2.y) * (p3.x - p4.x); // (y1 - y2) * (x3 - x4)
const d = d1 - d2;
if (d == 0) {
throw new Error('Number of intersection points is zero or infinity.');
}
// upper part of intersection point formula
const u1 = p1.x * p2.y - p1.y * p2.x; // (x1 * y2 - y1 * x2)
const u4 = p3.x * p4.y - p3.y * p4.x; // (x3 * y4 - y3 * x4)
const u2x = p3.x - p4.x; // (x3 - x4)
const u3x = p1.x - p2.x; // (x1 - x2)
const u2y = p3.y - p4.y; // (y3 - y4)
const u3y = p1.y - p2.y; // (y1 - y2)
// intersection point formula
const px = (u1 * u2x - u3x * u4) / d;
const py = (u1 * u2y - u3y * u4) / d;
const p = { x: px, y: py };
return p;
};
// Usage example:
interface Point {
x: number;
y: number;
}
// line 1
const p1: Point = { x: 85, y: 45 }; // P1: (x1, y1)
const p2: Point = { x: 260, y: 180 }; // P2: (x2, y2)
// line 2
const p3: Point = { x: 225, y: 75 }; // P3: (x4, y4)
const p4: Point = { x: 65, y: 260 }; // P4: (x4, y4)
// result
const p: Point = calculateIntersection(p1, p2, p3, p4); // intersection point
console.log('P=(' + p.x + '; ' + p.y + ')');
Output:
P=(184.53682260305698; 121.78554886521538)