Angular D3 理解 attrTween 函数

maa*_*aac 3 javascript d3.js typescript angular

我试图了解如何在 D3 中使用 attrTween 函数。我正在尝试从以下示例中实现饼图:http : //bl.ocks.org/mbostock/5100636

然而,当我到达过渡部分时,我遇到了问题。

  private populateGauge(): void {
    const innerRadius = this.radius - 50;
    const outerRadius = this.radius - 10;
    const arc = d3
      .arc()
      .innerRadius(innerRadius)
      .outerRadius(outerRadius)
      .startAngle(0);

    const background = this.svg
      .append('path')
      .datum({ endAngle: this.tau })
      .style('fill', '#ddd')
      .attr('d', arc);
    this.myEndAngle = { endAngle: (this.gaugeData.value / 100) * this.tau };
    const foreground = this.svg
      .append('path')
      .datum(this.myEndAngle)
      .style('fill', 'orange')
      .attr('d', arc);

    foreground
      .transition()
      .duration(1500)
      .attrTween('d', function(newAngle) {
        return function(d) {
          const interpolate = d3.interpolate(d.endAngle, newAngle);
          return function(t) {
            d.endAngle = interpolate(t);
            return arc(d);
          };
        };
      });
    }
Run Code Online (Sandbox Code Playgroud)

错误

我一直在尝试使用简单的基本情况,只是在插值函数中使用 0,但我无法摆脱最后一个返回语句抛出的最终错误(返回弧(d));

“number”类型的参数不能分配给“DefaultArcObject”类型的参数。

我如何解决这些问题?如果您需要提供更多信息,请告诉我。

Rea*_*lar 5

attrTween('d',...)接受一个返回另一个函数的函数。您向它传递一个函数,该函数以当前数据索引和当前节点作为参数被调用。此函数应返回使用时间值调用的插值函数。

当我查看您的源代码时。您有 3 个嵌套函数,这是不正确的。

你需要有开始结束的角度作为的价值基准,并且不应该发生变异数据从一个补间函数内部。

我更喜欢在tween函数之外创建一个arc函数,然后将它用于我的插值。哪个更有效,因为您不是每次都创建一个新的函数。

const myArc = d3.arc();
// ^^^ call methods of arc() to configure settings that won't animate.

foreground
  .transition()
  .duration(1500)
  .attrTween('d', (d) => {
      return (t) => {
        const angle = d3.interpolate(d.endAngle, d.newAngle)(t);
        // ^^^ interpolate datum values using time.
        myArc.startAngle(angle);
        // ^^^ call methods of arc() to configure what you need.
        return myArc(null);
        // ^^^ call arc function to render "d" attribute.
      };
    };
  });
Run Code Online (Sandbox Code Playgroud)

我发现使用节点包“@types/d3”更容易

npm install @types/d3 --save-dev
Run Code Online (Sandbox Code Playgroud)

然后你可以将这些类型导入到 TypeScript 文件中

import * as d3 from 'd3';
Run Code Online (Sandbox Code Playgroud)

如果您有像 WebStorm 这样的 IDE。您可以在 D3 函数上按 CTRL+CLICK 并查看类型定义和注释。