RudiSophieson
RudiSophieson

Reputation: 271

Repeated (chained) transitions D3js

I've already had a look at all the examples on chained/repeated transitions out there (e.g. http://bl.ocks.org/mbostock/1125997), but I can't bring my example to work.

I try to reapeat a transition an infinite number of times, but somehow as the first transition ends, the position of the three circles changes. My goal is to call the starting positions of the circles as transition ends and run the transition again and again and again...

Here's my code.

var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width = 800 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var svg = d3.select("body")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);

var dataset = [20, 100, 180];

var circle = svg.selectAll("circle")
                   .data(dataset)
                   .enter()
                   .append("circle")
                       .attr("cx", function(d) { return d; })
                       .attr("cy", function(d) { return d; })
                       .attr("r", 5)
                    .transition()
                        .duration(2000)
                        .attr("cx", function(d) {return d + 80; })
                        .attr("cy", function(d) {return d + 80; })
                        .each("end", repeat)
                        .remove();


function repeat(){

    var circle = svg.selectAll("circle")
                   .data(dataset)
                   .enter()
                   .append("circle")
                       .attr("cx", function(d) { return d; })
                       .attr("cy", function(d) { return d; })
                       .attr("r", 5)
                    .transition()
                        .duration(2000)
                        .attr("cx", function(d) {return d + 80; })
                        .attr("cy", function(d) {return d + 80; })
                        .each("end", repeat)
                        .remove();


};

Here's my working example: https://jsfiddle.net/RudiSophieson/1vkwkbks/2/

Thanks in advance.

Upvotes: 1

Views: 283

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

In the repeat function you don't need to append the circle again. You just need to update the cx and cy.

var circle = svg.selectAll("circle")
                        .attr("cx", function(d) { return d; })
                   .attr("cy", function(d) { return d; })
                   .attr("r", 5)
                .transition()
                    .duration(2000)
                    .attr("cx", function(d) {return d + 80; })
                    .attr("cy", function(d) {return d + 80; })
                    .each("end", repeat)
                    .remove();

working code here

Upvotes: 3

Related Questions