判断两个矩形区域是否相交

第一种

/**
 * 判断两个区域是否相交
 * 判断A的left或right 是否在B的left-right区间内
 * &&
 * 判断A的top或bottom 是否在B的top-bottom区间内
 * */

const isRectOverlap = (rectA?: DOMRect, rectB?: DOMRect): boolean => {
  if (!rectA || !rectB) return false;

  const { left: leftA, right: rightA, bottom: bottomA, top: topA } = rectA;
  const { left: leftB, right: rightB, bottom: bottomB, top: topB } = rectB;

  const isInRowArea = (pointX: number) => leftB <= pointX && pointX <= rightB;
  const isInColArea = (pointY: number) => topB <= pointY && pointY <= bottomB;

  const isOverlapRow = isInRowArea(leftA) || isInRowArea(rightA);
  const isOverlapCol = isInColArea(topA) || isInColArea(bottomA);

  return isOverlapRow && isOverlapCol;
};

第二种

const isRectOverlap = (rect1?: DOMRect, rect2?: DOMRect): boolean => {
  if (!rect1 || !rect2) {
    return false;
  }
  const [l1, t1, r1, b1] = [
    rect1.x,
    rect1.y,
    rect1.x + rect1.width,
    rect1.y + rect1.height,
  ];
  const [l2, t2, r2, b2] = [
    rect2.x,
    rect2.y,
    rect2.x + rect2.width,
    rect2.y + rect2.height,
  ];

  return !(l1 > r2 || r1 < l2 || t1 > b2 || b1 < t2);
};

使用:

  const targetNode = hotArea.getBoundingClientRect();
  const currentNode = optionArea.getBoundingClientRect();

  const isInHotArea = isRectOverlap(targetNode, currentNode);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值