D3中的动画折线图

时间:2019-12-24 10:40:31

标签: angular d3.js

我在d3中找到了动画线系列的example

我正在尝试用自己的TS代码制作相同的动画。

但不成功。

// Start Animation on Click
d3.select("#start").on("click", function() {
    var path = svg.append("path")
        .datum(data)
        .attr("class", "line")
        .attr("d", line);

    // Variable to Hold Total Length
    var totalLength = path.node().getTotalLength();

    // Set Properties of Dash Array and Dash Offset and initiate Transition
    path
        .attr("stroke-dasharray", totalLength + " " + totalLength)
        .attr("stroke-dashoffset", totalLength)
    .transition() // Call Transition Method
        .duration(4000) // Set Duration timing (ms)
        .ease(d3.easeLinear) // Set Easing option
        .attr("stroke-dashoffset", 0); // Set final value of dash-offset for transition
});

// Reset Animation
d3.select("#reset").on("click", function() {
    d3.select(".line").remove();
});

如何将以上代码嵌入我的角度代码中。 数据正在从API获取。尽管图表工作正常,但我只需要根据参考添加动画。

private drawPath(): void {
    let city = this.g
      .selectAll(".city")
      .data(this.TEMPERATURES)
      .enter()
      .append("g")
      .attr("fill", "transparent")
      .attr("class", "city")
      .style("stroke", "transparent");

    city
      .append("path")
      .attr("class", "line")
      .attr("d", d => this.line(d.values))
      .style("stroke", function(d) {
        return d.color;
      });

    let totalLength = city.length;
    console.log(totalLength, "Length total");

    city
      .append("text")
      .datum(function(d) {
        return { id: d.id, value: d.values[d.values.length - 1] };
      })
      .attr(
        "transform",
        d =>
          "translate(" +
          this.x(d.value.date) +
          "," +
          this.y(d.value.temperature) +
          ")"
      )
      .attr("x", 3)
      .attr("dy", "0.35em")
      .transition()
      .style("font", "10px sans-serif")
      .text(function(d) {
        return d.id;
      });
  }

根据@SmokeyShakers得出的结果 enter image description here

1 个答案:

答案 0 :(得分:1)

您的totalLength计算不正确。根据您的示例进行操作:

let totalLength = city.select('.line').node().getTotalLength();

city.select('.line')
    .attr("stroke-dasharray", totalLength + " " + totalLength)
    .attr("stroke-dashoffset", totalLength)
    .transition() // Call Transition Method
    .duration(4000) // Set Duration timing (ms)
    .ease(d3.easeLinear) // Set Easing option
    .attr("stroke-dashoffset", 0);