如何在d3.transition期间正确访问SVG元素的变换

问题描述 投票:0回答:1

我正在使用d3.transitions在圆上使用d3动画。

假设具有以下圆形动画(d3.transition()):

animationTime = 500;
svg = d3.select('#svg');                      // Select the SVG by its id previously added to the DOM
circle = d3.select('#circleid')               // Select a circle by its id from the SVG
           .transform('translate(0,0)');      // Set position of that circle to origin

circle.transition().duration(animationTime)   // Start an animation with transition time of 0.5 sec
      .transform('translate(500,500)');       // Animate position of circle to new position (500, 500)

console.log(circle.attr('transform'));    // --> Output: 'translate(50,50)'
setTimeout(() => { 
   console.log(circle.attr('transform')); // --> Output: 'translate(500,500)'
}, animationTime + 50);                   // without +50 the animation is not completely finished, yet

我当前的解决方案是引入地图或元素属性以保存最终位置并访问SVGElement属性而不是进行转换,这使这种定位方式的管理更加复杂。看到这里:

animationTime = 500;
svg = d3.select('#svg');                      
circle = d3.select('#circleid')               
           .transform('translate(0,0)');      

circle.attr('final-x', 500).attr('final-y', 500)   // Save final position as separate attribute
      .transition().duration(animationTime)   
      .transform('translate(500,500)');       

console.log(circle.attr('final-x'), circle.attr('final-y'));  // Output --> 500 500

这里,值是正确的,但是需要附加属性每个元素

因此,我认为这不是适当的解决方案...

如何解决此问题的标准d3方法是什么?有没有一种方法可以访问元素的最终转换状态而无需其他属性/数据结构?我不想不必要地用垃圾填充DOM。

关于如何以良好方式执行此操作的任何想法?

javascript animation d3.js transition
1个回答
0
投票

A transition.end event listener可以添加到代码中,并将提供转换结束时的值。

下面的摘要中的演示。

transition.end
animationTime = 500;
circle = d3.select('#circleid')               // Select a circle by its id from the SVG
           .attr('transform', 'translate(0,0)');      // Set position of that circle to origin

let t = circle.transition().duration(animationTime)   // Start an animation with transition time of 0.5 sec
      .attr('transform', 'translate(500,500)')       // Animate position of circle to new position (500, 500)

t.on('end', function() {
    console.log(circle.attr('transform'))
})
© www.soinside.com 2019 - 2024. All rights reserved.