I have this small area chart demo done in d3.js.
I’m able to animate the chart as a whole but can’t find a way to animate it piece-by-piece (I want it to be a proper animation, not a simple reveal using svg-clip). For example the code to animate the circles in the page linked above is just 2 simple lines that I’ve broken up here for clarity:
// start frame
chart
.selectAll( 'circle' )
.data( data )
.enter()
.append( 'circle' )
.attr( 'cx', function( d, i ) { return x( i ); })
.attr( 'cy', y( 0 ) )
.attr( 'class', 'point' ).attr( 'r', 5 );
// end frame
chart
.selectAll( 'circle' )
.data( data )
.transition()
.duration( 3000 )
.attr( 'cx', function( d, i ) { return x( i ); })
.attr( 'cy', function( d, i ) { return y( d ); });
The problem here is that all the circles start and finish at once. The same happens with the segments of the area chart. So how do I move them one after another? One way is to use d3’s delay function; I’m not sure how I would do this for the path segments of the area chart but for the circles marking the data points, it’d be something like this:
// start frame
chart
.selectAll( 'circle' )
.data( data )
.enter()
.append( 'circle' )
.attr( 'cx', function( d, i ) { return x( i ); })
.attr( 'cy', y( 0 ) )
.attr( 'class', 'point' ).attr( 'r', 5 );
// end frame
chart
.selectAll( 'circle' )
.data( data )
.transition()
.delay( 1000 * c )
.duration( 3000 )
.attr( 'cx', function( d, i ) { return x( i ); })
.attr( 'cy', function( d, i ) { return y( d ); });
But to do this, I need c, the handle linking to individual circles one after the other, as if in a loop.
So my questions are:
-
How do I get
c, the handle to an individual element of a
selection, for the circles and for the area (svg.area()) chart? -
Is there a simpler way to achieve this than my
delayapproach?
1) The
cyou’re looking for can be gotten by passing a function intodelay(), exactly in the same way you do for anyattr()call (see documentation):2) Using
delay()sure seems like the right approach for this.AFAIK, you’re still going to have difficulties doing the same for the path. I can’t come up with any way to do this other than animating the underlying data points themselves.