SVG中setMatrix方法设置图形变换不生效问题排查
失效原因
你的setMatrix调用不生效是两个基础错误导致的:
- 调用语法错误:
setMatrix是函数方法,必须用圆括号()传参调用,你代码里前两处用了访问属性的方括号[],第三处甚至写成了setMatrix1, [数组]的错误语法,全程没有真正执行过setMatrix方法。 - 参数类型错误:
setMatrix不接受零散数字、普通数组作为入参,它要求传入一个合法的SVGMatrix矩阵实例,你直接写6个数字的写法完全不符合接口参数规范。
正确调用方式
setMatrix的正确使用流程如下:
- 通过SVG根元素的
createSVGMatrix()方法创建空矩阵实例 - 给矩阵实例的
a/b/c/d/e/f六个属性赋值,分别对应2D变换矩阵的六个参数(水平缩放、垂直倾斜、水平倾斜、垂直缩放、水平偏移、垂直偏移) - 用圆括号调用
setMatrix(你创建的矩阵实例)完成变换配置 - 把配置好的变换项追加到元素的transform列表中,最后按需合并即可
修正后的可运行代码:
const svgns = 'http://www.w3.org/2000/svg' const svg = d3.select('svg'); height = 400; width = 720; svg .attr('xmlns', svgns) .attr('viewBox', `0 0 ${width} ${height}`) svg.append('rect') .attr('class', 'vBoxRect') .style("overflow", "visible") .attr('width', `${width}`) .attr('height', `${height}`) .attr('stroke', 'black') .attr('fill', 'transparent'); const green = document.querySelector('.green'); const svgRoot = green.ownerSVGElement; const transformList = green.transform.baseVal; // 第一个变换:对应translate(50,90) const trans1 = svgRoot.createSVGTransform(); const mat1 = svgRoot.createSVGMatrix(); mat1.a = 1; mat1.b = 0; mat1.c = 0; mat1.d = 1; mat1.e = 50; mat1.f = 90; trans1.setMatrix(mat1); transformList.appendItem(trans1); // 第二个变换:对应rotate(-45) const trans2 = svgRoot.createSVGTransform(); const mat2 = svgRoot.createSVGMatrix(); const angle = -45 * Math.PI / 180; mat2.a = Math.cos(angle); mat2.b = Math.sin(angle); mat2.c = -Math.sin(angle); mat2.d = Math.cos(angle); mat2.e = 0; mat2.f = 0; trans2.setMatrix(mat2); transformList.appendItem(trans2); // 第三个变换:对应translate(30,160) const trans3 = svgRoot.createSVGTransform(); const mat3 = svgRoot.createSVGMatrix(); mat3.a = 1; mat3.b = 0; mat3.c = 0; mat3.d = 1; mat3.e = 30; mat3.f = 160; trans3.setMatrix(mat3); transformList.appendItem(trans3); // 合并所有变换,运行后绿色圆形会和红色圆形完全重合 transformList.consolidate();
如果追求更简洁的写法,可以直接计算三个变换相乘后的总矩阵,只需要调用一次setMatrix就能实现完全一致的效果,不需要追加三次变换项。
内容的提问来源于stack exchange,提问作者smpa01
相关产品推荐
相关产品推荐

