How to convert CSS transform matrix back to its component properties

[亡魂溺海] 提交于 2020-02-01 03:20:47

问题


I have obtained a CSS transform matrix of an element by using getComputedStyle() method as follows.

var style = window.getComputedStyle(elem1, null);
var trans = style.transform;

trans = matrix(1, 0, 0, 1, 1320, 290)

Is there a way to back calculate the transform matrix to get the original CSS rules ie. the values to translate , rotate, skew properties. I'm assuming it can be calculated by reversing the method used to form the matrix. P.S. - The values of transform properties are given in percentages, I want to back calculate these percentage values from the matrix.

CSS transform - transform: translate(200%, 500%);


回答1:


Yes, it's possible to do that!

The parameters to matrix come in this order: matrix(scaleX(),skewY(),skewX(),scaleY(),translateX(),translateY())

Read more about it here

If you want to retrieve the numbers from that string (matrix(1,0,0,1,720,290) you could use this regex:

style = window.getComputedStyle(elem1, null);
trans = style.transform;
numberPattern = /-?\d+\.?\d*/g;

values = trans.match( numberPattern );

This will return the following array:

["1", "0", "0", "1", "720", "290"]

Edit after comments

The values returned in the window.getComputedStyle are the computed values (i.e. the percentages you used are being parsed to pixel values). You can reverse that calculation, but you need to know what the percentage is using to figure out how many pixels it should be.

Enter CSS3 Transforms

One interesting thing about CSS transforms is that, when applying them with percentage values, they base that value on the dimensions of the element which they are being implemented on, as opposed to properties like top, right, bottom, left, margin, and padding, which only use the parent's dimensions (or in case of absolute positioning, which uses its closest relative parent). Source

if you use the following calculation, you should be able to get the percentages you used:

style = window.getComputedStyle(elem1, null);
trans = style.transform;
numberPattern = /-?\d+\.?\d+|\d+/g;

values = trans.match( numberPattern );

computedTranslateX = values[4];
computedTranslatey = values[5];

xPercentage = (computedTranslateX / elem1.offsetWidth) * 100;
yPercentage = (computedTranslateY / elem1.offsetHeight) * 100;


来源:https://stackoverflow.com/questions/43065579/how-to-convert-css-transform-matrix-back-to-its-component-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!