设置我的D3项目,该项目在屏幕上具有许多要动画的形状(Org
类)。我正在尝试维护一个面向对象的范例,并利用D3动画(https://jrue.github.io/coding/2014/lesson07/)。
考虑下面的代码:
function test() {
class Org {
constructor(_width, _height) {
this.width = _width;
this.height = _height;
}
}
var orgs = [];
var canvas = d3.select('body')
.append('svg')
.attr('width', screen.width)
.attr('height', screen.height);
for (var x = 0; x < 100; x++) {
var circle = new Org(Math.random()*screen.width, Math.random()*screen.height);
orgs.push(circle);
canvas.append('circle')
.attr('cx', circle.width)
.attr('cy', circle.height)
.attr('r', 5)
.attr('fill', 'pink');
}
for (var b = 0; b < orgs.length; b++) {
circle.transition().attr('cx', 0); //DOES NOT WORK
}
}
显然,注释行引发错误,因为它transition()
属于D3,而不是我的班级。如何选择这些对象并对它们进行动画处理?
您的代码不是D3- ish,这使得实现您的目标变得很麻烦。请记住,D3本质上是关于数据驱动的文档的,因此,数据绑定是其核心。了解这一概念对于充分利用该库至关重要。相应地重构代码时,解决方案几乎显而易见。
也就是说,在处理D3时,使用for循环总是看起来很可疑。很少需要使用这些循环,因为D3的内部工作可以解决这些问题。在不破坏OO方法的情况下,您可以将orgs
数组绑定到选择区域,并利用D3的魔力:
var circles = canvas.selectAll("circle")
.data(orgs)
.enter().append('circle')
.attr('cx', d => d.width )
.attr('cy', d => d.height )
.attr('r', 5)
.attr('fill', 'pink');
这会将圆圈添加到您选择Org
的orgs
数组中,该圆圈对应于您数组中使用绑定到选择的所有实例.data(orgs)
。上面的语句还保留了对该选择的引用,该选择在circles
变量中包含所有新添加的圆,您可以将其用于以后的操作。
进行过渡时,此参考资料会派上用场:
circles
.transition()
.attr('cx', 0);
请看以下与您的方法相同的代码段,但它是D3方式。
class Org {
constructor(_width, _height) {
this.width = _width;
this.height = _height;
}
}
var orgs = d3.range(100).map(function() {
return new Org(Math.random() * screen.width, Math.random() * screen.height);
});
var canvas = d3.select('body')
.append('svg')
.attr('width', screen.width)
.attr('height', screen.height);
var circles = canvas.selectAll("circle")
.data(orgs)
.enter().append('circle')
.attr('cx', d => d.width )
.attr('cy', d => d.height )
.attr('r', 5)
.attr('fill', 'pink');
circles
.transition()
.attr('cx', 0);
<script src="https://d3js.org/d3.v4.js"></script>
您可能需要看一些有关此概念的教程,以进行更深入的介绍:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句