Skip to content

Instantly share code, notes, and snippets.

@alijaya
Created November 18, 2020 10:40
Show Gist options
  • Save alijaya/51fb485565cae64c2dff34117e43d004 to your computer and use it in GitHub Desktop.
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
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