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

标签 javascript html css css-transforms

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

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

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

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

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

最佳答案

是的,这是可能的!

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

阅读更多相关信息 here

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

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

values = trans.match( numberPattern );

这将返回以下数组:

["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

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

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;

关于javascript - 如何将 CSS 变换矩阵转换回其组件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43065579/

相关文章:

html - CSS 保持元素最大顶部和左侧

javascript - 打印应用了 CSS 样式的 Angular 网页

css - 进度条 100% 宽度与 css

javascript - 如何使用 three.js 在运行时绘制线段

javascript - 具有完整时间设置的嵌套 JQuery 动画

html - 背景图像高度和覆盖内容溢出和重复

html - CSS 类不适用于 div

html - CSS中的 'ex'单元有什么用?

javascript - contenteditable 选定的文本保存和恢复

javascript - 我们可以将 highcharts 图例更改为单选按钮而不是复选框样式吗?