Created
November 18, 2020 10:40
-
-
Save alijaya/51fb485565cae64c2dff34117e43d004 to your computer and use it in GitHub Desktop.
To transform coordinate from offset space (padding box of element) to page space
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
export function parseOrigin(transformOrigin) { | |
return transformOrigin.split(" ").map(parseFloat); | |
} | |
export function getElementMatrix(element) { | |
const matrix = new DOMMatrix(); | |
let current = element; | |
while (current) { | |
const computedStyle = window.getComputedStyle(current); | |
const origin = parseOrigin(computedStyle.transformOrigin); | |
const transformMatrix = new DOMMatrix(computedStyle.transform); | |
const originMatrix = new DOMMatrix(); | |
originMatrix.translateSelf(origin[0], origin[1]); | |
const invOriginMatrix = originMatrix.inverse(); | |
const offsetMatrix = new DOMMatrix(); | |
offsetMatrix.translateSelf(current.offsetLeft, current.offsetTop); | |
const clientMatrix = new DOMMatrix(); | |
clientMatrix.translateSelf(current.clientLeft, current.clientTop); | |
matrix.preMultiplySelf(clientMatrix); | |
matrix.preMultiplySelf(invOriginMatrix); | |
matrix.preMultiplySelf(transformMatrix); | |
matrix.preMultiplySelf(originMatrix); | |
matrix.preMultiplySelf(offsetMatrix); | |
current = current.offsetParent; | |
} | |
return matrix; | |
} | |
export function getElementInverseMatrix(element) { | |
return getElementMatrix(element).inverse(); | |
} | |
export function offsetToPage(element, point) { | |
return getElementMatrix(element).transformPoint(point); | |
} | |
export function pageToOffset(element, point) { | |
return getElementInverseMatrix(element).transformPoint(point); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment