#98 判断两个矩形是否重叠

用一个对象的数据来表示一个矩形的位置和大小:

{
  x: 100,
  y: 100,
  width: 150,
  height: 250
}

它表示一个宽为 150 高为 250 的矩形在页面上的 (100, 100) 的位置。

请你完成一个函数 isOverlap 可以接受两个矩形作为参数,判断这两个矩形在页面上是否重叠。例如:

const rect1 = { x: 100, y: 100, width: 100, height: 100 }
const rect2 = { x: 150, y: 150, width: 100, height: 100 }
isOverlap(rect1, rect2) // => true
const isOverlap = (rect1, rect2) => {
    // rect1中x的范围[rect1_x1, rect1_x2],y的范围[rect1_y1, rect1_y2]
    const rect1_x1 = rect1.x;
    const rect1_x2 = rect1.x + rect1.width;
    const rect1_y1 = rect1.y;
    const rect1_y2 = rect1.y + rect1.height;
    
    // rect2中x的范围[rect2_x1, rect2_x2],y的范围[rect2_y1, rect2_y2]
    const rect2_x1 = rect2.x;
    const rect2_x2 = rect2.x + rect2.width;
    const rect2_y1 = rect2.y;
    const rect2_y2 = rect2.y + rect2.height;

    if(rect1_x1 > rect2_x2 || rect1_x2 < rect2_x1 || rect1_y1 > rect2_y2 || rect1_y2 < rect2_y1) {
        return false;
    }
    else {
        return true;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值