contain.js 2.4 KB

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