Skip to content Skip to sidebar Skip to footer

D3 Chaining Animations With A For Loop

I want to chain d3 animations over a for loop. What is the best way to achive something like this: for (var i=0; i

Solution 1:

You can use transition.delay() to chain transitions. https://github.com/mbostock/d3/wiki/Transitions#wiki-delay

for (var i = 0; i < dat.length - 1; i++) {
    g.transition().duration(20).delay(i * 20)
        .attr("cy", dat[i + 1].y1)
        .attr("cx", dat[i + 1].x1);
}

Solution 2:

I found a solution that works for me. I feel it is still ugly code but at least it works.

First I create an unvisible object for each data in my dataset:

g.data(dat) 
.enter()
.append("circle")
.attr("class", function(d,i) { return "default " + d.pn; })
.attr("cx", function(d,i) { return d.x1; })
.attr("cy", function(d,i) { return d.y1; })
.attr("r",  function(d,i) { return d.r; })
.style("opacity", 0);

And then I am going to shedule a transition for each single element:

        g.each(function(d,i){
            var delay = Math.floor((i+1) / nrOfElements);
            //console.log(delay);
            d3.select(this)
                .transition()
                .delay(delay * speed)
                .duration(speed + DELAY_OFFSET)
                .style("opacity", 100)
                .attr("cx", function(d) { return i<dat.length-1 ? dat[i+1].x1 : dat[i].x1; })
                .attr("cy", function(d) { return i<dat.length-1 ? dat[i+1].y1 : dat[i].y1; })
                .attr("r",  function(d) { return i<dat.length-1 ? dat[i+1].r : dat[i].r; })
                .style("stroke", "blue") // TODO: setAttributes
                .each("end", function() { 
                    // Reset to privious attributes
                    d3.select(this)
                        .attr("cx", function(d) { return dat[i].x1; })
                        .attr("cy", function(d) { return dat[i].y1; })
                        .attr("r",  function(d) { return dat[i].r; })
                        ;

                    if(i<dat.length-nrOfElements) d3.select(this).style("opacity", 0); 
                })
                ;
        });

This seems a huge effort in coding to me for a rather simple requirement ... but at least it is working ..

Better solutions are still welcome!!


Post a Comment for "D3 Chaining Animations With A For Loop"