geometry.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. export const isPointInsideRect = (point, rect) =>
  2. point.x > rect.left &&
  3. point.x < rect.left + rect.width &&
  4. point.y > rect.top &&
  5. point.y < rect.top + rect.height;
  6. export const distance = (point1, point2) => {
  7. const x = point2.x - point1.x;
  8. const y = point2.y - point1.y;
  9. return Math.sqrt(x * x + y * y);
  10. };
  11. // See https://github.com/substack/point-in-polygon/blob/master/nested.js
  12. /*const pointInPolygon_ = ({ x, y }, vs) => {
  13. var inside = false;
  14. for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
  15. var xi = vs[i][0],
  16. yi = vs[i][1];
  17. var xj = vs[j][0],
  18. yj = vs[j][1];
  19. var intersect =
  20. yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
  21. if (intersect) inside = !inside;
  22. }
  23. return inside;
  24. };*/
  25. export const isPointInPolygon = ({ x, y }, vs) => {
  26. var inside = false;
  27. for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
  28. var xi = vs[i].x,
  29. yi = vs[i].y;
  30. var xj = vs[j].x,
  31. yj = vs[j].y;
  32. var intersect =
  33. yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
  34. if (intersect) inside = !inside;
  35. }
  36. return inside;
  37. };
  38. // Links
  39. // http://jeffreythompson.org/collision-detection/rect-rect.php
  40. const vectorCenter = (point1, point2) => {
  41. return { x: (point1.x + point2.x) / 2, y: (point1.y + point2.y) / 2 };
  42. };
  43. export const rectRadius = (rect, center) => {
  44. const midP1A = vectorCenter(rect[0], rect[1]);
  45. const midP1B = vectorCenter(rect[1], rect[2]);
  46. const midP1 = vectorCenter(midP1A, midP1B);
  47. return distance(center, midP1);
  48. };