intersect-rect.js 702 B

1234567891011121314151617181920212223242526272829303132
  1. function intersectRect (node, point) {
  2. const x = node.x
  3. const y = node.y
  4. // Rectangle intersection algorithm from:
  5. // http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes
  6. const dx = point.x - x
  7. const dy = point.y - y
  8. let w = node.width / 2
  9. let h = node.height / 2
  10. let sx, sy
  11. if (Math.abs(dy) * w > Math.abs(dx) * h) {
  12. // Intersection is top or bottom of rect.
  13. if (dy < 0) {
  14. h = -h
  15. }
  16. sx = dy === 0 ? 0 : h * dx / dy
  17. sy = h
  18. } else {
  19. // Intersection is left or right of rect.
  20. if (dx < 0) {
  21. w = -w
  22. }
  23. sx = w
  24. sy = dx === 0 ? 0 : w * dy / dx
  25. }
  26. return {x: x + sx, y: y + sy}
  27. }
  28. export default intersectRect