4

I have an element 3D transformed something like this:

.foo {
  transform: rotateX(-30deg) rotateY(35deg);
}

Now I want to get these values via javascript. It's easy to get the 3D matrix:

var matrix = $('.foo').css('transform');
// return:
// matrix3d(0.819152, -0.286788, -0.496732, 0, 0, 0.866025, -0.5, 0, 0.573576, 0.409576, 0.709406, 0, 0, 0, 0, 1)

But is it possible to calculate CSS like values -30 and 35 with that matrix? I just found ways to do this for 2D transforms.

1

1 Answer 1

6

Ok, got it!

var _getTransform = function($element) {

    var matrix = $element.css('transform'),
        rotateX = 0,
        rotateY = 0,
        rotateZ = 0;

    if (matrix !== 'none') {

        // do some magic
        var values = matrix.split('(')[1].split(')')[0].split(','),
            pi = Math.PI,
            sinB = parseFloat(values[8]),
            b = Math.round(Math.asin(sinB) * 180 / pi),
            cosB = Math.cos(b * pi / 180),
            matrixVal10 = parseFloat(values[9]),
            a = Math.round(Math.asin(-matrixVal10 / cosB) * 180 / pi),
            matrixVal1 = parseFloat(values[0]),
            c = Math.round(Math.acos(matrixVal1 / cosB) * 180 / pi);

        rotateX = a;
        rotateY = b;
        rotateZ = c;

    }

    return {
        rotateX: rotateX,
        rotateY: rotateY,
        rotateZ: rotateZ
    };

}
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, thanks for the function. I've got a question though: the returned values are obviously between 0 and 90 degrees. How can we get a value which is from 0 and 360?
for 0 to 360: c = Math.round(Math.atan2(values[1], values[0]) * 180 / pi); if (c < 0) { c = 360 + c; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.