In D3.JS Is there a way to add on to a line, one point at a time, using D3 transition?

 ̄綄美尐妖づ 提交于 2019-12-11 07:23:39

问题


I'm trying to draw a line where by clicking a button, the line "grows" to a further x and y point that are the next numbers in the data array while the previous x and y points that have already been "drawn" remain there.

I was able to successfully make this work by adding X2 and Y2 attributes to my line on a click function, but I'd like it to be so where you click again, the line grows to the next X and Y point in the data array: dataGDP[2].date and dataGDP[2].GDPreal.

    var realGDPline = canvasGDP.append("line")
   .attr("class", "line")
   .attr("x1", xScaleGDP(dataGDP[0].date))
   .attr("y1", yScaleGDP(dataGDP[0].GDPreal));

...on the click function:

     realGDPline
    .transition()
    .duration(1200)
    .attr("x2", xScaleGDP(dataGDP[1].date))
    .attr("y2", yScaleGDP(dataGDP[1].GDPreal));

Are there examples online if this somewhere too?

Here is my JS Fiddle on what I've been working on so far: http://jsfiddle.net/RL_NewtoJS/yvdC7/2/

I also have a circle and text that moves/updates with the click function, and that seems to work by adding 1 to a variable called "counter" and using that variable to select the next data point in the array, but I'm not sure if this can be applied to the line somehow too.


回答1:


I would use a line generator instead of line elements.

To prevent funky transitions when adding a point to the end of the line, our line generator will have an number of points equal to the number of total elements in the data set. Extra points which are not visible yet stack up on the of the line on the last point.

var lineGen = d3.svg.line()
    .x(function(d, i){
      return xScaleGDP(i <= counter ? d.date : dataGDP[counter].date); })
    .y(function(d, i){
      return yScaleGDP(i <= counter ? d.GDPreal : dataGDP[counter].GDPreal); })

Add a path to the DOM, attaching the data and drawing points:

var pathLine = canvasGDP.append('path').datum(dataGDP)
    .attr('d', lineGen)
    .classed('line', true)

On click, we recalculate the path and transition to it:

pathLine.transition().duration(1200)
    .attr('d', lineGen)

http://bl.ocks.org/1wheel/7743519



来源:https://stackoverflow.com/questions/20318833/in-d3-js-is-there-a-way-to-add-on-to-a-line-one-point-at-a-time-using-d3-trans

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