简体   繁体   中英

apply a transition on each object in a D3 selection

I'm having troubles in understanding how to get each D3 object in a selection to apply a transition. Consider the follwoing code (here on jsfiddle ):

var svg = d3.select('svg');

var dataSet = [10, 20, 30, 40];

var circle = svg.selectAll('circle')
    .data(dataSet)
    .enter()
    .append('circle')
    .attr("r",function(d){ return d })
    .attr("cx", function(d, i){ return i * 100 + Math.random()*50 })
    .attr("cy",50)
    .attr("fill",'red')
   ;

circle.each(function(d,i) {
    this
  .transition()
  .duration(1000)
  .attr("cx",this.cx+100);
})

My use of this is wrong. I've also tried with d3.select(this) but I get the dom object corresponding to D3 object. I'm unable to get the D3 object to apply transition.

The missing part is that you can supply a function to .attr('cx', function (d,i) { ... }) when using a transition, and inside that function you can access the cx attribute using this.getAttribute('cx') .

Of course, you also want to make sure to turn it into a number using parseInt() , otherwise it will do string concatenation (because JS, sigh).

So change your final line to:

circle.transition().duration(1000).attr('cx', function(d, i) {
  return parseInt(this.getAttribute('cx')) + 100;
});

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