如何将 CSS 变换矩阵转换回其组件属性

How to convert CSS transform matrix back to its component properties

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

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

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

有没有办法反向计算变换矩阵以获得原始 CSS 规则,即。平移、旋转、倾斜属性的值。我假设它可以通过反转用于形成矩阵的方法来计算。 P.S。 - 变换属性的值以百分比给出,我想从矩阵中反向计算这些百分比值。

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

是的,可以做到!

矩阵的参数顺序如下: matrix(scaleX(),skewY(),skewX(),scaleY(),translateX(),translateY())

了解更多信息 here

如果您想从该字符串 (matrix(1,0,0,1,720,290)) 中检索数字,您可以使用此正则表达式:

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

values = trans.match( numberPattern );

这将 return 以下数组:

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

评论后编辑

在 window.getComputedStyle 中输入的值 return 是计算值(即您使用的百分比被解析为像素值)。您可以反转该计算,但您需要知道百分比用于计算它应该是多少像素。

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

如果您使用以下计算,您应该能够得到您使用的百分比:

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;