Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.js - Animated exit for nested object

For each data item, I add a group (g class="parent") with a circle in it. Adding them and setting their properties works fine.

But I can't figure out how to handle removal. What's the way to animate a nested object on exit?

// parents
var parents = svg.selectAll("parent").data(glyphs);
parents.enter()
    .append("g")
    .attr("class", "parent")
    .attr("transform", function (glyph) { 
        return "translate(" + glyph.x + "," + glyph.y + ")";
    });

// children
var circles = parents.append("circle");
circles
    .attr("r", 0)
    .attr("fill", function (glyph) { return glyph.color; });
// animated entry
circles.transition()
    .attr("r", function (glyph) { return glyph.radius; });

Here's the part that isn't working. I'm not sure how to animate the children on exit.

// animate exit
circles
    .exit() // <-- not valid
    .transition()
    .duration(250)
    .attr("r", 0);
parents
    .exit()
    .transition()
    .delay(250)
    .remove();

Could anyone offer some tips or point me to a good example?

like image 332
sharoz Avatar asked Dec 17 '13 01:12

sharoz


1 Answers

The data is bound to the parents, thus you need to add the enter / transition / exit for the circles in relation to the parents:

function draw(glyphs){
  console.log(glyphs)
  // parents
  var parents = svg.selectAll(".parent").data(glyphs);
  parents.enter()
    .append("g")
    .attr("class", "parent")
    .attr("transform", function (glyph) { 
        return "translate(" + glyph.x + "," + glyph.y + ")"; 
    })
    // Parent's data enter -> add circle -> do entry animation
    .append("circle")
      .attr("r", 0)
      .attr("fill", function (glyph) { return glyph.color; })
      .transition()
        .duration(250)
        .attr("r", function (glyph) { return glyph.radius; });

  // parents data changes -> select circles -> transition nested circles
  parents.select("circle")
   .transition()
     .duration(250)
     .attr("r", function (glyph) { return glyph.radius; });

  // Parent's data exit -> select circle -> do exit animation    
  parents.exit()
    .select("circle")
      .transition()
      .duration(250)
      .attr("r", 0);

  // Delay removal of parent for 250.
  parents.exit()
    .transition()
    .duration(250)
    .remove();    
}

draw(glyphs);

setTimeout(function(){
  draw(glyphs.map(function(g){g.radius = g.radius + 20; return g;}));
}, 1000);

setTimeout(function(){
  glyphs.pop();
  glyphs.pop();
  glyphs.pop();
  glyphs.pop();
  glyphs.pop();
  draw(glyphs);
}, 3000);

Here's an example: http://jsfiddle.net/3M4xh/2/

like image 61
minikomi Avatar answered Nov 10 '22 07:11

minikomi