关于javascript:如何将CSS转换矩阵转换回其组件属性

How to convert CSS transform matrix back to its component properties

我已经通过使用getComputedStyle()方法获得了元素的CSS变换矩阵,如下所示。

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

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

有没有一种方法可以向后计算转换矩阵以获得原始CSS规则,即。 转换,旋转,倾斜属性的值。 我假设可以通过反转用于形成矩阵的方法来计算。
附言 -转换属性的值以百分比给出,我想从矩阵中反算这些百分比值。

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


是的,有可能这样做!

矩阵的参数按以下顺序排列:
matrix(scaleX(),skewY(),skewX(),scaleY(),translateX(),translateY())

在这里了解更多

如果要从该字符串(矩阵(1,0,0,1,720,290))中检索数字,则可以使用以下正则表达式:

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

values = trans.match( numberPattern );

这将返回以下数组:

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

评论后编辑

在window.getComputedStyle中返回的值是计算得出的值(即,将您使用的百分比解析为像素值)。 您可以逆转该计算,但是您需要知道该百分比用于确定应有多少像素。

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

如果使用以下计算,则应该能够获得所使用的百分比:

1
2
3
4
5
6
7
8
9
10
11
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;