Last active
March 7, 2017 02:18
-
-
Save johnlaine1/101a3bf6815c4fafa5cf66ddc61624a3 to your computer and use it in GitHub Desktop.
A function that finds the rectangle intersection of 2 rectangles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const findRangeOverlap = (point1, length1, point2, length2) => { | |
const highestStartPoint = Math.max(point1, point2); | |
const lowestEndPoint = Math.min(point1 + length1, point2 + length2); | |
if (highestStartPoint >= lowestEndPoint) { | |
return {startPoint: null, width: null}; | |
} | |
const overlapLength = lowestEndPoint - highestStartPoint; | |
return {startPoint: highestStartPoint, overlapLength: overlapLength}; | |
}; | |
const getRectangleIntersection = (r1, r2) => { | |
const x = findRangeOverlap(r1.leftx, r1.width, r2.leftx, r2.width); | |
const y = findRangeOverlap(r1.bottomY, r1.height, r2.bottomY, r2.height); | |
if (!x.overlapLength || !y.overlapLength) { | |
return { | |
leftx: null, | |
bottomY: null, | |
width: null, | |
height: null | |
}; | |
} | |
return { | |
leftx: x.startPoint, | |
bottomY: y.startPoint, | |
width: x.overlapLength, | |
height: y.overlapLength | |
}; | |
}; | |
// Example data | |
const rectangle1 = { | |
leftx: 3, | |
bottomY: 2, | |
width: 5, | |
height: 2 | |
}; | |
const rectangle2 = { | |
leftx: 6, | |
bottomY: 2, | |
width: 2, | |
height: 4 | |
}; | |
return getRectangleIntersection(rectangle1, rectangle2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment