R.Atim
R.Atim

Reputation: 387

Javascript/jQuery How to get the value of a scale from a matrix value

A matrix is acquired first.

this.getMatrix = function(obj)
{
    var matrix = obj.css("-webkit-transform") ||
                 obj.css("-moz-transform")    ||
                 obj.css("-ms-transform")     ||
                 obj.css("-o-transform")      ||
                 obj.css("transform");
    return matrix;
};

And the value of a scale is acquired.

this.getScaleDegrees = function(obj)
{
    var matrix = this.getMatrix(obj),
        matrixRegex = /matrix\((-?\d*\.?\d+),\s*0,\s*0,\s*(-?\d*\.?\d+),\s*0,\s*0\)/,
        matches = matrix.match(matrixRegex);
    return matches;
};

And the value of a rotate is acquired.

this.getRotationDegrees = function(obj)
{
    var matrix = this.getMatrix(obj),
        angle = 0;

    if(matrix !== 'none') {
        var values = matrix.split('(')[1].split(')')[0].split(','),
            a = values[0],
            b = values[1];
        angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
    }

    return angle;
};

Now, I am faced with a problem.
The function 'getScaleDegrees' failed, when there are both of rotations and scales of an element.
Since the function 'getRotationDegrees' operates normally,
I think that I will edit the function 'getScaleDegrees' with the help of process of the function 'getRotationDegrees'.

So, question is how to get the value of a scale.

Any good ideas or calculation methods?


EDIT:

There is a function to change a scale and rotation and the value of a scale and rotation is different each time. The value which the function 'getMatrix' returns becomes such this.

none [no rotate & no scale]  
matrix(1.2, 0, 0, 1.2, 0, 0) [edit scale]  
matrix(0.965926, -0.258819, 0.258819, 0.965926, 0, 0) [edit rotate]  
matrix(1.3523, -0.362347, 0.362347, 1.3523, 0, 0) [edit rotate & edit scale]

Upvotes: 4

Views: 7853

Answers (1)

R.Atim
R.Atim

Reputation: 387

One of the solution was made.

convert matrix to array (thanx eicto)

this.parseMatrix = function(_str)
{
    return _str.replace(/^matrix(3d)?\((.*)\)$/,'$2').split(/, /);
};

get the value of a scale

this.getScaleDegrees = function(obj)
{
    var matrix = this.parseMatrix(this.getMatrix(obj)),
        scale = 1;

    if(matrix[0] !== 'none') {
        var a = matrix[0],
            b = matrix[1],
            d = 10;
        scale = Math.round( Math.sqrt( a*a + b*b ) * d ) / d;
    }

    return scale;
};

'Math.sqrt( a*a + b*b )' referred to CSS-TRICKS.

Upvotes: 2

Related Questions