Rectangles intersection
by Alex Myronov
JavaScript
/* intersected */
const rectangle1 = {
leftX: 1,
bottomY: 1,
width: 4,
height: 2,
}
const rectangle2 = {
leftX: 3,
bottomY: 2,
width: 3,
height: 4,
}
/* not intersected */
/* const rectangle1 = {
leftX: 1,
bottomY: 1,
width: 3,
height: 2,
}
const rectangle2 = {
leftX: 4,
bottomY: 3,
width: 1,
height: 2,
}
*/
function intersectPoints(p1Start, p1End, p2Start, p2End) {
const highestStart = p1Start > p2Start ? p1Start : p2Start
const lowestEnd = p1End > p2End ? p2End : p1End
if (lowestEnd <= highestStart) {
return null
}
return {
start: highestStart,
length: lowestEnd - highestStart,
}
}
function intersection(rect1, rect2) {
const sizeX = intersectPoints(rect1.leftX, rect1.leftX + rect1.width, rect2.leftX, rect2.leftX + rect2.width)
const sizeY = intersectPoints(rect1.bottomY, rect1.bottomY + rect1.height, rect2.bottomY, rect2.bottomY + rect2.height)
if (!sizeX || !sizeY) return null
return {
leftX: sizeX.start,
bottomY: sizeY.start,
width: sizeX.length,
height: sizeY.length,
}
}
console.log(intersection(rectangle1, rectangle2))