Animate line chart in d3

两盒软妹~` 提交于 2020-08-26 09:03:08

问题


I find the example of animated line series in d3.

I am trying to do the same animation in my TS code.

but its not successful.

// 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();
});

how can I embed the above code in my angular code. The Data is fetching from API. Although the charts working perfectly fine, I need to just add the animation as per reference.

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;
      });
  }

Result as per @SmokeyShakers


回答1:


Your totalLength calculation isn't right. Working from your example:

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); 


来源:https://stackoverflow.com/questions/59467526/animate-line-chart-in-d3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!