D3 Chaining Animations with a for loop

落花浮王杯 提交于 2020-01-06 08:26:05

问题


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<dat.length-1; i++) {
        var a = function(g,dat,i){
            /*
            g.transition().duration(i * 19)
                .attr("cy", dat[i+1].y1)
                .attr("cx", dat[i+1].x1)
                .attr("r", 10);*/
            console.log("transform " + dat[i+1].x1);
        };

        var t = setTimeout(a(g,dat,i), i*20);
    }

This is of corse not working, since you can not pass objects to setTimeout functions.


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



回答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!!



来源:https://stackoverflow.com/questions/14120435/d3-chaining-animations-with-a-for-loop

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