循环d3过渡有限次

时间:2018-12-08 16:41:37

标签: javascript animation d3.js

我正在创建一系列的圆,并且我希望将其半径转换有限的次数。这是最初绘制圆圈的代码:

this.node = this.svg.append('g')
  .attr('class', 'nodes')
  .selectAll('circle')
  .data( self.nodesArray )
  .enter().append('circle')
  .attr('class', 'node-deals' )
  .attr('cx', d => d.x)
  .attr('cy', d => d.y )
  .attr('r', (d, i) => self.totalDealsArray[i] )
  .attr('fill', (d, i) => self.nodeColor[i] );

我可以找到有关链接转换的所有示例和stackoverflow帖子,它们可以链接预定数量的转换或无限循环。我需要能够对动态数量的循环使用相同的代码,所以我一直在尝试for循环:

update() {
  self = this;

  var t = d3.transition()
    .duration(750)
    .delay(750);

  var nodeAnimation = svg.selectAll('circle.node-deals')
    .data(self.dealsArray);

  for (let j = 0; j < this.dealsArray.length; j++ ) {
    nodeAnimation
      .transition(t)
      .attr('r', (d) => {
        return self.dealsArray[j]} );
  }
}

但是过渡仅发生一次。它不会按预期重复。<​​/ p>

1 个答案:

答案 0 :(得分:1)

您需要链接转换

var nodes = [
  {x:50, y:50, color:"red", total:25},
  {x:125, y:25, color:"green", total:20},
  {x:100, y:75, color:"blue", total:10}
];

var svg = d3.select('#chart');
svg.append('g')
  .attr('class', 'nodes')
  .selectAll('circle')
  .data( nodes )
  .enter().append('circle')
  .attr('class', 'node-deals' )
  .attr('cx', d => d.x)
  .attr('cy', d => d.y )
  .attr('r', d => d.total )
  .attr('fill', d => d.color );

var dealsArray = [40, 10, 50, 5, 25];
var animation = svg.selectAll('circle.node-deals')
    .transition()
    .duration(250); // wait 250+750ms before animation

for (let j = 0; j < dealsArray.length; j++ ) {
  animation = animation.transition()
    .duration(750)
    .delay(750)
    .attr('r', d => dealsArray[j] );
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg id="chart" width="500" height="500"/>

相关问题