LineIntersect.js 1.0 KB

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