Search code examples
javascriptanimationd3.jssvg-animate

D3 speed issue with link animation in directed graph


I am trying to animate the links on a force layout directed graph using the code below. The links are simple lines and not paths. I initiate the animation with a button press. The style change (in onTick) happens immediately but the problem is that the animation itself takes about 10 seconds to start. Am I doing something wrong? Can I speed up the start of the animation. I have to say that once the animation starts, the animation runs very well.

function animLink( d )
{
    this.transition()
        .delay(0)
        .duration(10000)
        .ease( "linear" )
        .attrTween( "stroke-dashoffset", function() {
            var i = d3.interpolateString( "1000", "0" );
            return function(t) { return i(t); };
        } )
    .each( "end", function() { d3.select(this).call(animLink); } );
}

onTick = function(e)
{
    if (buttonPressed)
        link
            .style( "stroke-dasharray", "10,10" )
            .call( animLink );
}

You can see a jsfiddle here. In the beginning there is a 5 second delay even though I am specifying .delay(0).

The graph in the fiddle is pretty small compared to the 2000 nodes I have in mine.


Solution

  • The problem is that you're calling the code that starts the animation at every iteration (i.e. tick event) of the force layout. That is, you're setting it up over and over again so that it doesn't actually have a chance to run because new transitions cancel old ones.

    When it actually runs it's because the force layout has settled down and there are no more tick events. Solution: call the code outside the tick event handler. Demo here.