我是d3
的新手,正在尝试学习基础知识,我画了一个圆圈,想使用函数调用对其进行更新。
此代码可以正常工作并绘制一个圆圈:
const svg = d3.select('svg');
svg.append('g').selectAll('circle')
.data([50])
.enter()
.append('circle')
.attr('cy', 60)
.attr('cx', 100)
.attr('r', function(d) { return d; });
现在,我创建一个函数,该函数需要一个数组来更新data
属性并更改圆的半径:
function update(data) {
const circle = svg.select('g').select('circle').data(data);
circle.enter().append('circle').attr('r', function(d) { return d; });
}
update([100])
如果我调用console.log(circle.data())
,则该值已正确设置,但可悲的是,该圆在屏幕上的半径仍然是50px。
答案 0 :(得分:0)
在D3数据绑定(d3.select(s).data(d)
)中,我们应该准备做三件事:
enter
,它为数据中尚未选择的DOM中的每个元素添加了一个几何图形,
transition
,它使用新数据更改DOM中的每个选定元素,并且
exit
,如果我们的数据少于所选DOM中的元素,则会从DOM中删除元素。
对于您而言,您只需要更新update()
函数即可执行以下三个操作:
<!DOCTYPE html>
<meta charset="utf-8">
<head></head>
<body>
<svg width="1500" height="920"></svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script>
const svg = d3.select('svg');
svg.append('g').selectAll('circle')
.data([50])
.enter()
.append('circle')
.attr('cy', 600)
.attr('cx', 700)
.attr('r', function(d) { return d; })
.attr('fill', 'red');
function update(data) {
const circle = svg.select('g').select('circle').data(data);
circle.enter()
.append('circle')
.attr('r', function(d) { return d; });
circle.transition()
.attr('r', function(d) { return d; });
circle.exit()
.remove()
}
setTimeout(function() {
update([100])
}, 500)
</script>
</body>
</html>
您的方法遇到的麻烦是您没有在更新函数中调用transition
。我们需要使用过渡来修改与所选内容匹配的元素。
如果您想更多地查看数据绑定,我在这里整理了一下tutorial on data binding in D3,可能会有帮助。