Jason Mayo
Jason Mayo

Reputation: 356

jQuery Matrix Values from CSS

I'm trying to get Matrix values from CSS transform properties, but for some reason it's not working.

var object = $(this);

var transMatrix = object.css("-webkit-transform") || 
                  object.css("-moz-transform") || 
                  object.css("-ms-transform") || 
                  object.css("-o-transform") || 
                  object.css("transform");

console.log("Matrix = " + transMatrix);

var values = transMatrix.split('(')[1];
    values = transMatrix.split(')')[0];
    values = transMatrix.split(',');

console.log("Values = " + values);

var a = values[0];
console.log("a = " + a);
var b = values[1];
console.log("b = " + b);

var scale = Math.sqrt(a*a + b*b);
console.log("Scale = " + scale);                                        

var sin = b/scale;
console.log("Sin = " + sin);

var transScale = Math.round(scale * 100) / 100;
console.log("Transform Scale = " + transScale);

var transAngle = Math.round(Math.asin(sin) * (180/Math.PI));
console.log("Transform Angle = " + transAngle);

But when I output this, console shows:

Matrix = matrix(0.496273075820661, 0.06093467170257374, -0.06093467170257374, 0.496273075820661, 0, 0)
Values = matrix(0.496273075820661, 0.06093467170257374, -0.06093467170257374, 0.496273075820661, 0, 0)
a = matrix(0.496273075820661
b =  0.06093467170257374
Scale = NaN
Sin = NaN
Transform Scale = NaN
Transform Angle = NaN 

It seems to be returning 'undefined' after it's got the Matrix values from the CSS (Which is working correctly)

Is there something wrong with my 'split' method?

Upvotes: 2

Views: 1639

Answers (1)

Blazemonger
Blazemonger

Reputation: 92903

var values = transMatrix.split('(')[1];
values = transMatrix.split(')')[0];
values = transMatrix.split(',');

should be

var values = transMatrix.split('(')[1];
values = values.split(')')[0];
values = values.split(',');

or simply chain them:

var values = transMatrix.split('(')[1].split(')')[0].split(',');

In fact, you can do this a little more cleanly using regular expressions and .match:

var values = transMatrix.match(/[\d\.]+/g);

Upvotes: 3

Related Questions