contain.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { getBounds } from './bounds';
  2. function onLine(line, point) {
  3. return (point[0] <= Math.max(line[0][0], line[1][0]) &&
  4. point[0] <= Math.min(line[0][0], line[1][0]) &&
  5. point[1] <= Math.max(line[0][1], line[1][1]) &&
  6. point[1] <= Math.min(line[0][1], line[1][1]));
  7. }
  8. function direction(a, b, c) {
  9. var val = (b[1] - a[1]) * (c[0] - b[0]) - (b[0] - a[0]) * (c[1] - b[1]);
  10. if (val === 0)
  11. return 0;
  12. return val < 0 ? 2 : 1;
  13. }
  14. function isIntersect(line1, line2) {
  15. var dir1 = direction(line1[0], line1[1], line2[0]);
  16. var dir2 = direction(line1[0], line1[1], line2[1]);
  17. var dir3 = direction(line2[0], line2[1], line1[0]);
  18. var dir4 = direction(line2[0], line2[1], line1[1]);
  19. if (dir1 !== dir2 && dir3 !== dir4)
  20. return true;
  21. if (dir1 === 0 && onLine(line1, line2[0]))
  22. return true;
  23. if (dir2 === 0 && onLine(line1, line2[1]))
  24. return true;
  25. if (dir3 === 0 && onLine(line2, line1[0]))
  26. return true;
  27. if (dir4 === 0 && onLine(line2, line1[1]))
  28. return true;
  29. return false;
  30. }
  31. export function isPointInsideRectangle(polygon, point) {
  32. var n = polygon.length;
  33. if (n < 3)
  34. return false;
  35. var lineToInfinity = [point, [9999, point[1]]];
  36. var count = 0;
  37. var i = 0;
  38. do {
  39. var side = [polygon[i], polygon[(i + 1) % n]];
  40. if (isIntersect(side, lineToInfinity)) {
  41. if (direction(side[0], point, side[1]) === 0)
  42. return onLine(side, point);
  43. count++;
  44. }
  45. i = (i + 1) % n;
  46. } while (i !== 0);
  47. return !!(count & 1);
  48. }
  49. export function isRectangleBInsideA(rectA, rectB) {
  50. return rectB.every(function (point) { return isPointInsideRectangle(rectA, point); });
  51. }
  52. /**
  53. * 检测 child 是否完全在 container 内部
  54. */
  55. export function contain(container, child, margin) {
  56. var x1 = container.x1, x2 = container.x2, y1 = container.y1, y2 = container.y2;
  57. var parent = [
  58. [x1, y1],
  59. [x2, y1],
  60. [x2, y2],
  61. [x1, y2],
  62. ];
  63. var element = getBounds(child, margin);
  64. return isRectangleBInsideA(parent, element);
  65. }
  66. //# sourceMappingURL=contain.js.map