There will be no unique solution for any particular installation, but you can easily find one of the solutions with this algorithm:
- Find the rectangle inside A, which is above the rectangle B. If the vertex A is higher than B (i.e., has a lower value in px), then such a rectangle exists. This rectangle is defined as follows: (left edge A, upper edge A) - (right edge A, upper edge B).
- If the left edge of B is to the right of the left edge of A, the following rectangle is: (left edge of A, min (upper edge of A, upper edge of B)) to (left edge of B, max (lower edge of A, lower edge of B))
- If the right edge of B is to the left of the right edge of B, similarly above
- ... and a possible rectangle below B
In total, you will get from 0 to 4 rectangles.
Pseudo-code with a somewhat unusual but understandable definition of a rectangle:
function getClipped(A, B) { var rectangles = []; if (A.top < B.top) { rectangles.push({ left: A.left, top: A.top, right: A.right, bottom: B.top }); } if (A.left < B.left) { rectangles.push({ left: A.left, top: max(A.top, B.top), right: B.left, bottom: min(A.bottom, B.bottom) }); } if (A.right > B.right) { rectangles.push({ left: B.right, top: max(A.top, B.top), right: A.right, bottom: min(A.bottom, B.bottom) }); } if (A.bottom > B.bottom) { rectangles.push({ left: A.left, top: B.bottom, right: A.right, bottom. A.bottom }); } return rectangles; } var rectA = { left: nn, top: nn, right: nn, bottom: nn}; var rectB = { left: nn, top: nn, right: nn, bottom: nn}; var clipped = getClipped(rectA, rectB) ;
dan.p source share