Skip to main content

计算两个矩形重叠面积

· 2 min read
Alan

算法解释

算法逻辑来自 两个矩形的相交面积,怎么求算法效率相对较高? - ying xiong的回答 - 知乎

假设矩形的边都平行于坐标轴,分别表示为(left1,top1,right1,bottom1), (left2,top2,right2,bottom2),则相交部分必定也是矩形,算 长 x 宽 就可以.

相交部分的宽,可以看成两个矩形的宽,在x轴上的投影的长度, 也就是两条线段的总长度,减去重叠之后新线段的长度. 按下图示意,算出 A+B-W 就可以了: 示意图

用矩形坐标套进去,就是 overlapX = (right1-left1)+(right2-left2) - ( max(right1,right2) - min(left1,left2) )不管A B两条线段怎么移来移去,谁长谁短,这个式子都不变的,如果是 <=0,自然是没有相交.

同理再算出高就可以了。

作者:ying xiong 链接:https://www.zhihu.com/question/28854765/answer/42331859 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

JavaScript实现

/**
* 计算重叠面积
* @param {{left: number, right: number, top: number, bottom: number}} pos1
* @param {{left: number, right: number, top: number, bottom: number}} pos2
*/
function elementInterectArea(pos1, pos2) {
const pos1Width = pos1.right - pos1.left;
const pos1Height = pos1.bottom - pos1.top;
const pos2Width = pos2.right - pos2.left;
const pos2Height = pos2.bottom - pos2.top;

const axisOverlap = pos1Width + pos2Width - (Math.max(pos1.right, pos2.right) - Math.min(pos1.left, pos2.left));
const crossOverlap = pos1Height + pos2Height - (Math.max(pos1.bottom, pos2.bottom) - Math.min(pos1.top, pos2.top));
if (axisOverlap <= 0 || crossOverlap <= 0) {
return 0;
}
return axisOverlap * crossOverlap;
}

// 下面计算两个HTML元素的重叠面积
const area = elementInterectArea(element1.getBoundingClientRect(), element2.getBoundingClientRect());

将遮住元素全部删除JS hide-verlap.js.