Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read/parse individual transform style values in JavaScript?

Webkit's blog post from last year on 3D transforms explains the various transform 'functions' that can be used in the -webkit-transform property. For example:

#myDiv {
  -webkit-transform: scale(1.1) rotateY(7deg) translateZ(-1px);
}

My question: how do you access individual values in JavaScript? When you read the webkitTransform property of the element, you just get a matrix3d() function with 16 values in it, like this...

matrix3d(0.958684, 0.000000, .....)

Is there a way to just read the value of an individual transform thing, like rotateY()? Or do I have to read it from the matrix3d() string, and how?

like image 851
callum Avatar asked Aug 07 '10 23:08

callum


People also ask

What is translateX in Javascript?

The translateX() CSS function repositions an element horizontally on the 2D plane. Its result is a <transform-function> data type.

What is CSS individual transform properties?

The transform CSS property lets you rotate, scale, skew, or translate an element. It modifies the coordinate space of the CSS visual formatting model.

What is transform in Javascript?

The transform property applies a 2D or 3D transformation to an element. This property allows you to rotate, scale, move, skew, etc., elements.


2 Answers

// Suppose the transformed element is called "cover".
var element = document.getElementById('cover');
computedStyle = window.getComputedStyle(element, null); // "null" means this is not a pesudo style.
// You can retrieve the CSS3 matrix string by the following method.
var matrix = computedStyle.getPropertyValue('transform')
    || computedStyle.getPropertyValue('-moz-transform')
    || computedStyle.getPropertyValue('-webkit-transform')
    || computedStyle.getPropertyValue('-ms-transform')
    || computedStyle.getPropertyValue('-o-transform');

// Parse this string to obtain different attributes of the matrix.
// This regexp matches anything looks like this: anything(1, 2, 3, 4, 5, 6);
// Hence it matches both matrix strings:
// 2d: matrix(1,2,3,4,5,6)
// 3d: matrix3d(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
var matrixPattern = /^\w*\((((\d+)|(\d*\.\d+)),\s*)*((\d+)|(\d*\.\d+))\)/i;
var matrixValue = [];
if (matrixPattern.test(matrix)) { // When it satisfy the pattern.
    var matrixCopy = matrix.replace(/^\w*\(/, '').replace(')', '');
    console.log(matrixCopy);
    matrixValue = matrixCopy.split(/\s*,\s*/);
}

Hope this helps! Note that I did not use another library except plain DOM API and native Javascript RegExp function. Hence, this should work universally cross browsers and application.

like image 200
lixiang Avatar answered Sep 20 '22 16:09

lixiang


Old but interesting question and no previous response has attempted to answer it.

Unfortunately there's no two-liner solution for the general case and we don't know about what variety of transform steps (rotate, translate etc.) need to be reverse engineered; the fewer the easier.

In recent webkit based browsers, one can simply query the previously assigned property:

var element = document.querySelector('div.slipping');
element.style.webkitTransform 
  -> "translate(-464px, 0px)"

Let's continue with the assumption that the computed style needs to be used. The need arises, for example, if the element is in the middle of a CSS transition or CSS animation, i.e. the current transformation is not one that was set directly.

The matrix descriptor string returned by getComputedStyle can indeed be parsed via a regex, but not all versions above are reliable, and they're too opaque. A straightforward way to break down the string, unless it's in a very tight loop to warrant a single-pass regex, is this:

var matrixString = window.getComputedStyle(element).webkitTransform;
var matrix = matrixString
             .split('(')[1]
             .split(')')[0]
             .split(',')
             .map(parseFloat);

But another way is to simply use this, which wasn't mentioned before:

var cssMatrix = new WebKitCSSMatrix(matrixString);

The benefit of the latter approach is that you get back a 4x4 matrix as well, which is the standard representation for affine transformations, and the drawback is that it's of course WebKit specific. Should you continue to work with the tuple of six values as in the question, it's defined in this part of the CSS standard.

Then the transform, e.g. rotation needs to be reverse engineered. There can be many simple transforms directly supported by CSS, e.g. translate, scale, rotate, skew, and perspective. If only one of them is applied, then you just need to revert the process of computing the transform matrix.

An alternative is to find or translate code which does this for you in JS, e.g. the same document or Section 7.1 of the CSS standard contains such annotated algorithms. The benefit is that the unmatrix approach is able to, with some limitations, return the 'atomic' transforms even if more than one of these (translate, rotate etc.) is applied. Since it's not possible to guarantee the successful reverse engineering of the transform steps for the general case, it's useful to think about what types of transforms are possibly applied, and whether degenerate or other troublesome cases have been avoided. I.e. you need to build the solution as you see fit for your problem.

Specifically, the matrix versions of all 2D CSS transforms are documented here as well, below the meaning of the six values in the CSS 2D transform vector.

Another caveat is that there are other things that influence the visual outcome in terms of geometric operations, for example, transform-origin.

like image 27
Robert Monfera Avatar answered Sep 19 '22 16:09

Robert Monfera