UNPKG

d3plus-shape

Version:

Fancy SVG shapes for visualizations

26 lines (25 loc) 1.19 kB
/** @function lineIntersection @desc Finds the intersection point (if there is one) of the lines p1q1 and p2q2. @param {Array} p1 The first point of the first line segment, which should always be an `[x, y]` formatted Array. @param {Array} q1 The second point of the first line segment, which should always be an `[x, y]` formatted Array. @param {Array} p2 The first point of the second line segment, which should always be an `[x, y]` formatted Array. @param {Array} q2 The second point of the second line segment, which should always be an `[x, y]` formatted Array. @returns {Boolean} */ export default function (p1, q1, p2, q2) { // allow for some margins due to numerical errors var eps = 1e-9; // find the intersection point between the two infinite lines var dx1 = p1[0] - q1[0], dx2 = p2[0] - q2[0], dy1 = p1[1] - q1[1], dy2 = p2[1] - q2[1]; var denom = dx1 * dy2 - dy1 * dx2; if (Math.abs(denom) < eps) return null; var cross1 = p1[0] * q1[1] - p1[1] * q1[0], cross2 = p2[0] * q2[1] - p2[1] * q2[0]; var px = (cross1 * dx2 - cross2 * dx1) / denom, py = (cross1 * dy2 - cross2 * dy1) / denom; return [px, py]; }