SVGTransform: matrix 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

SVGTransform 接口的只读属性 matrix 表示与转换 type 对应的变换矩阵。

如果直接更改 matrix 对象(即不使用 SVGTransform 接口本身的方法) ,则 SVGTransformtype 会更改为 SVG_TRANSFORM_MATRIX

  • 对于 SVG_TRANSFORM_MATRIX,矩阵包含用户提供的 a、b、c、d、e、f 值。

  • 对于 SVG_TRANSFORM_TRANSLATE,e 和 f 代表平移量(a=1、b=0、c=0 且 d=1)。

  • 对于 SVG_TRANSFORM_SCALE,a 和 d 代表缩放量(b=0、c=0、e=0 且 f=0)。

  • 对于 SVG_TRANSFORM_SKEWXSVG_TRANSFORM_SKEWY,a、b、c 和 d 代表将导致给定倾斜的矩阵(e=0 且 f=0)。

  • 对于 SVG_TRANSFORM_ROTATE,a、b、c、d、e 和 f 一起代表将导致给定旋转的矩阵。当围绕中心点 (0, 0) 旋转时,e 和 f 将为零。

一个活动的 DOMMatrix 对象。

示例

访问和修改矩阵

html
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <rect id="rect" x="50" y="50" width="100" height="100" fill="red" />
</svg>
js
const rect = document.getElementById("rect");
const transformList = rect.transform.baseVal;

// Create and add a rotation transform
const rotateTransform = rect.ownerSVGElement.createSVGTransform();
rotateTransform.setRotate(30, 100, 100); // Rotate 30 degrees
transformList.appendItem(rotateTransform);

// Access the matrix
const matrix = transformList.getItem(0).matrix;
console.log(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f);

// Modify the matrix directly
matrix.a = 2; // Double the horizontal scaling
console.log(transformList.getItem(0).type); // Output: 1 (SVG_TRANSFORM_MATRIX)

理解变换类型

html
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <rect id="rect" x="50" y="50" width="100" height="100" fill="blue" />
</svg>
js
const rect = document.getElementById("rect");
const transformList = rect.transform.baseVal;

// Apply a translation transform
const translateTransform = rect.ownerSVGElement.createSVGTransform();
translateTransform.setTranslate(20, 30);
transformList.appendItem(translateTransform);

// Access the matrix
const matrix = transformList.getItem(0).matrix;
console.log(matrix.e, matrix.f); // Output: 20, 30
console.log(transformList.getItem(0).type); // Output: 2 (SVG_TRANSFORM_TRANSLATE)

规范

规范
Scalable Vector Graphics (SVG) 2
# __svg__SVGTransform__matrix

浏览器兼容性

另见