Created
June 20, 2025 04:58
-
-
Save rakeshta/fd844d7d1cf9a8c927ea9f6c60a60f92 to your computer and use it in GitHub Desktop.
Utility to get the bounding client rectangle of an element, accounting for any CSS transforms applied to it.
This file contains hidden or 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
/** | |
* Utility to get the bounding client rectangle of an element, | |
* accounting for any CSS transforms applied to it. | |
* | |
* This is useful for accurately determining the position and size of elements | |
* that may have a CSS transform applied (e.g., rotation, scaling, translation). | |
* | |
* @param element The DOM element for which to get the bounding rectangle. | |
* @returns The bounding rectangle of the element, accounting for any CSS transforms. | |
*/ | |
export function getBoundingClientRectWithTransform(element: Element): DOMRect { | |
const rect = element.getBoundingClientRect(); | |
const computedStyle = getComputedStyle(element); | |
const transform = computedStyle.transform; | |
if (transform === 'none') { | |
return rect; | |
} | |
// Parse transform matrix and apply to coordinates | |
const matrix = new DOMMatrix(transform); | |
const corners = [ | |
{ x: rect.left, y: rect.top }, | |
{ x: rect.right, y: rect.top }, | |
{ x: rect.right, y: rect.bottom }, | |
{ x: rect.left, y: rect.bottom }, | |
]; | |
const transformedCorners = corners.map((corner) => { | |
const point = new DOMPoint(corner.x, corner.y); | |
return point.matrixTransform(matrix); | |
}); | |
const minX = Math.min(...transformedCorners.map((p) => p.x)); | |
const minY = Math.min(...transformedCorners.map((p) => p.y)); | |
const maxX = Math.max(...transformedCorners.map((p) => p.x)); | |
const maxY = Math.max(...transformedCorners.map((p) => p.y)); | |
return new DOMRect(minX, minY, maxX - minX, maxY - minY); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment