简体   繁体   中英

d3 Animate Multiple SVG Lines

I'm trying to create multiple lines on a line graph one at a time. I've created an object array of about 100 lines in the below format:

var allLines = [{type: "linear", values: [1000, 2000, 3000]}, {}, ... {}];

var line = d3.svg.line()
    .defined(function (d) {
        return d != null;
    })
    .x(function (d, i) {
        return x(new Date(minYear + i, 1, 1));
    })
    .y(function (d) {
        return y(d);
    });

Now I want to draw each line, one at a time with a delay of about 250 milliseconds between each line. I've tried the below approach which I thought would work, but I must be missing something because it just waits 250ms and then draws all the lines.

svg.append('g')
    .attr('class', 'lineGroup')
    .selectAll('path')
    .data(allLines)
    .enter()
    .append('path')
    .attr('class', function (d) {
        return d.type;
    })
    .style('visibility', 'hidden')
    .attr('d', function (d) {
        return line(d.values);
    });

    function foo(transition) {
        transition
            .style('visibility', 'visible');
    }

    d3.select('.lineGroup').selectAll('path').transition().delay(250).call(foo);

Your basic approach is right, you just need to adjust the delay dynamically such that the later lines are drawn later. At the moment, the delay applies to all lines. To make it dynamic, you can use something like

svg.append("g")
   // etc
   .transition()
   .delay(function(d, i) { return i * 250; })
   .style('visibility', 'visible');

You can also do everything in one call, no need for a separate one after creating the lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM