LineIntersect.js 961 B

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * Returns the intersection between two line segments a and b.
  3. *
  4. * @param {Point} l1s
  5. * @param {Point} l1e
  6. * @param {Point} l2s
  7. * @param {Point} l2e
  8. *
  9. * @return {Point}
  10. */
  11. export default function lineIntersect(l1s, l1e, l2s, l2e) {
  12. // if the lines intersect, the result contains the x and y of the
  13. // intersection (treating the lines as infinite) and booleans for
  14. // whether line segment 1 or line segment 2 contain the point
  15. var denominator, a, b, c, numerator;
  16. denominator = ((l2e.y - l2s.y) * (l1e.x - l1s.x)) - ((l2e.x - l2s.x) * (l1e.y - l1s.y));
  17. if (denominator == 0) {
  18. return null;
  19. }
  20. a = l1s.y - l2s.y;
  21. b = l1s.x - l2s.x;
  22. numerator = ((l2e.x - l2s.x) * a) - ((l2e.y - l2s.y) * b);
  23. c = numerator / denominator;
  24. // if we cast these lines infinitely in
  25. // both directions, they intersect here
  26. return {
  27. x: Math.round(l1s.x + (c * (l1e.x - l1s.x))),
  28. y: Math.round(l1s.y + (c * (l1e.y - l1s.y)))
  29. };
  30. }