intersect-polygon.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import intersectLine from './intersect-line'
  2. /*
  3. * Returns the point ({x, y}) at which the point argument intersects with the
  4. * node argument assuming that it has the shape specified by polygon.
  5. */
  6. function intersectPolygon (node, polyPoints, point) {
  7. const x1 = node.x
  8. const y1 = node.y
  9. const intersections = []
  10. let minX = Number.POSITIVE_INFINITY
  11. let minY = Number.POSITIVE_INFINITY
  12. polyPoints.forEach(function (entry) {
  13. minX = Math.min(minX, entry.x)
  14. minY = Math.min(minY, entry.y)
  15. })
  16. const left = x1 - node.width / 2 - minX
  17. const top = y1 - node.height / 2 - minY
  18. for (let i = 0; i < polyPoints.length; i += 1) {
  19. const p1 = polyPoints[i]
  20. const p2 = polyPoints[i < polyPoints.length - 1 ? i + 1 : 0]
  21. const intersect = intersectLine(node, point,
  22. {x: left + p1.x, y: top + p1.y}, {x: left + p2.x, y: top + p2.y})
  23. if (intersect) {
  24. intersections.push(intersect)
  25. }
  26. }
  27. if (!intersections.length) {
  28. console.log('NO INTERSECTION FOUND, RETURN NODE CENTER', node)
  29. return node
  30. }
  31. if (intersections.length > 1) {
  32. // More intersections, find the one nearest to edge end point
  33. intersections.sort(function (p, q) {
  34. const pdx = p.x - point.x
  35. const pdy = p.y - point.y
  36. const distp = Math.sqrt(pdx * pdx + pdy * pdy)
  37. const qdx = q.x - point.x
  38. const qdy = q.y - point.y
  39. const distq = Math.sqrt(qdx * qdx + qdy * qdy)
  40. return (distp < distq) ? -1 : (distp === distq ? 0 : 1)
  41. })
  42. }
  43. return intersections[0]
  44. }
  45. export default intersectPolygon