【问题标题】:Changing transform values in SVG with D3.js使用 D3.js 更改 SVG 中的变换值
【发布时间】:2015-12-27 15:15:42
【问题描述】:

我在一个 SVG 中有几个 100 个文本元素,它们来自外部 SVG 编辑器,我想使用 D3.js 更改它们的矩阵变换。它们的水平缩放比例均为 1.1,我想将其更改为 1.05,并将矩阵格式转换为“translate(dx,dy)rotate(θ)skewX(φ)scale(kx,ky)”形式。我查看了 D3 API 以返回转换值,但不知道如何更改它们并将其放入新的转换表单中。

D3.JS API transform

这是我的代码

var titles = d3.selectAll(".text-title");

for (i = 0; i < titles.length; i++) {
  var titleTransform = d3.select(titles[i]).attr("transform");
  var titleScale = d3.transform(titleTransform).scale;

  //Change scale to 1.05 but keep the other transform values
}

这是我的 svg

<svg>
  <text transform="matrix(1.1 0 0 1 10 20)" class="text-title"> FOO </text>
  <text transform="matrix(1.1 0 0 1 50 30)" class="text-title">
    <tspan x="0" y="0">FOO</tspan>
    <tspan x="-1.9" y="15">BAR</tspan>
  </text>
  <text transform="matrix(1.1 0 0 1 20 80)" class="text-title">
    <tspan x="0" y="0">FOO</tspan>
    <tspan x="-.2" y="15">BAR</tspan>
  </text>
  <text transform="matrix(1.1 0 0 1 100 30)" class="text-title"> GRUNGE BAR</text>
  <text transform="matrix(1.1 0 0 1 100 50)" class="text-title">
    <tspan x="0" y="0">FUNKY</tspan>
    <tspan x="4.9" y="15">FOO</tspan>
  </text>
</svg>

还有一个Fiddle

【问题讨论】:

    标签: javascript d3.js svg transform


    【解决方案1】:

    选择不是一个可以迭代的数组,但是有一个 each 方法可以在所有元素上调用。在那之后,你可以做这样的事情......

    function foo(d, i) {
        var titleTransform = d3.transform(d3.select(this).attr("transform"));
        //Change scale to 1.05 but keep the other transform values
        titleTransform.scale[0] = 1.05
        d3.select(this).attr("transform", titleTransform);
    }
    var titles = d3.selectAll(".text-title").each(foo);
    

    fiddle

    【讨论】:

    • 好的,谢谢,我不知道选择,这正是我需要的!
    猜你喜欢
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 2014-05-02
    • 2021-02-08
    • 1970-01-01
    • 2016-01-27
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多