JSFiddle - React, Tailwind, and code Playground

by tfoller

JavaScript

const linesIntersect = (p1, p2, p3, p4) => {
	if (p2[0] == p3[0] && p2[1] == p3[1]) return p2;
	if (p1[0] == p4[0] && p1[1] == p4[1]) return p1;
	// Pt = P1 + (P2 - P1)t
	// Pv = P3 + (P4 - P3)v
	const [a, b, c, d, e, f, g, h] = [
		p1[0],
		p2[0] - p1[0],
		p3[0],
		p4[0] - p3[0],
		p1[1],
		p2[1] - p1[1],
		p3[1],
		p4[1] - p3[1],
	];
	const v = (b * (e - g) + f * (c - a)) / (h * b - f * d);
	if (isNaN(v)) console.error('linesIntersect() err v: ', p1, p2, p3, p4);
	const safe = Math.abs(b) >= Math.abs(f);
	const t = safe ? (c - a + d * v) / b : (g - e + h * v) / f;
	if (isNaN(t)) console.error('linesIntersect() err t: ', p1, p2, p3, p4);
  
  if(t >= 0 && t <= 1 && v >= 0 && v <= 1) {
  	const px = [a + b * t, e + f * t];
  	console.log(`intersection at ${px[0]}, ${px[1]}`);
  }
  else {
  	console.log('no intersection');
  }
};

// intersection

const line1 = [
[1, 2],
[5, 6]
];
const line2 = [
[0, 4],
[3, 2]
];

linesIntersect(...line1, ...line2);

// no intersection

const line3 = [
[1, 2],
[5, 6]
];
const line4 = [
[0, 4],
[3, 5] // <--
];

linesIntersect(...line3, ...line4);