Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the combined matrix of all CSS transforms of an element?

Using Javascript, I need to get the transformation matrix of an element. It might not have any transformations, but its parents might. How can I get the combined value that maps the screen coordinate space to the element's coordinate space?

<div style="transform:scale(3.0)">
    <div style="transform:scale(0.5)">
        <h1 id="fubar">What is my scale?</h1>
    </div>
</div>
<script>
     var a = document.querySelector("#fubar");

     // chrome: displays "none".
     // firefox: displays "matrix(1.5, 0, 0, 1.5, 0, 0)"
     // I need to get the firefox value in all browsers
     alert(window.getComputedStyle(a).transform);
</script>
like image 996
Steve Hanov Avatar asked Oct 29 '22 02:10

Steve Hanov


1 Answers

Calling getCombinedMatrix(element) will give you the combined matrix as an array.

function getCombinedMatrix(element) {
    var matrix = getMatrixOfElement(element);
    var node = element.parentNode;

    while(node && node instanceof Element) { // traverse dom tree
        var node_matrix = getMatrixOfElement(node);
        prependMatrix(matrix,node_matrix); // prepend matrix of parent node

        node = node.parentNode;
    }

    return matrix;
}

function getMatrixOfElement(element) {
    var matrix = [1,0,0,1,0,0]; // default matrix (no transforms)
    var raw_transform = window.getComputedStyle(element).transform;

    if (raw_transform && raw_transform !== 'none') {
                // remove string wrapper 'matrix(' and split into parts    
        var parts = raw_transform.slice(7,-1).split(','); 
        for(var i=0;i<parts.length;i++) {
            matrix[i] = parseFloat(parts[i]); // put string parts into matrix as float
        }
    }

    return matrix;
}

function prependMatrix(m1,m2) {
    // matrix multiplication
    var a1 = m1[0];
    var c1 = m1[2];
    var tx1 = m1[4];

    m1[0] = m2[0]*a1+m2[2]*m1[1];
    m1[1] = m2[1]*a1+m2[3]*m1[1];
    m1[2] = m2[0]*c1+m2[2]*m1[3];
    m1[3] = m2[1]*c1+m2[3]*m1[3];
    m1[4] = m2[0]*tx1+m2[2]*m1[5]+m2[4];
    m1[5] = m2[1]*tx1+m2[3]*m1[5]+m2[5];
}

NOTE: This does not take the transformOrigin into account, so rotations might cause wrong results.

like image 193
Manuel Otto Avatar answered Nov 14 '22 02:11

Manuel Otto