为什么这个 d3 示例中的圆圈不移动
Why don't the circles in this d3 example move?
我想在 d3 中绘制和重绘圆时测试性能。我不需要转换圆圈,只需批量替换数据即可。
我以为这个片段可以做到,但事实并非如此。
我怎样才能做到这一点?
'use strict';
var w = $('#outlet').width();
var h = $('#outlet').height();
function getRandomInSVG(max) {
return Math.floor(Math.random() * (max - 0 + 1)) + 0;
}
function getRandomCoord() {
var x = getRandomInSVG(w);
var y = getRandomInSVG(h);
return [x, y];
}
function addRandomData(container) {
var data = [];
for(var index = 0; index < 5000; index++) {
data[index] = getRandomCoord();
}
container.selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr('cx', function (d) {
return d[0];
})
.attr('cy', function (d) {
return d[1];
})
.attr('r', '1px')
.attr('fill', 'red');
}
var svg = d3.select('#outlet')
.append('svg:svg')
.attr('width', w)
.attr('height', h);
setInterval(function() {
console.log('add random data');
addRandomData(svg);
}, 1000);
<body>
<h1>D3 Fun!</h1>
<div id="outlet" style="height:600px;width:600px;">
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
</body>
你只有输入模式。要重绘,您需要调用更新模式,另请参阅 http://bost.ocks.org/mike/selection/#enter-update-exit
您必须更改 addRandomData 函数,如下所示:
function addRandomData(container) {
var data = [];
for(var index = 0; index < 5000; index++) {
data[index] = getRandomCoord();
}
var updateSel = container.selectAll('circle')
.data(data);
updateSel
.enter()
.append('circle');
updateSel
.attr('cx', function (d) {
return d[0];
})
.attr('cy', function (d) {
return d[1];
})
.attr('r', '1px')
.attr('fill', 'red');
}
您的问题的工作示例在这里。
相关文章:
- D3.js:如何在svg上移动鼠标时创建弹出事件
- 为什么这个 d3 示例中的圆圈不移动
- 在 d3.js 中绘制滚动/移动平均线
- d3.js:垂直移动线's与双线图的交点
- D3.js强制布局:动态添加节点;t随图的其余部分移动
- D3.js:缩放时,在2D图形中沿着直线移动圆
- 如何移动 SVG 在 D3 中的位置
- d3:应用 scale() 变换时元素移动
- D3.js从 tsv 移动到具有嵌套数组的 json
- 如何一次移动所有选定的节点?D3/JS.
- 在 D3 中移动固定节点
- D3.js基于鼠标移动的更新行
- 移动节点时如何停止平移?也限制缩放?D3.
- D3在鼠标上沿路径移动圆平移X轴上的直线时移动中断
- 使用d3.js移动折线图
- D3.js饼图.选中时可以移动饼图切片
- 使用d3动态地更新线使得线来回移动
- d3.js将节点和标签一起移动
- D3,当上下文发生变化时,第二焦点不会移动
- D3.js Fisheeye.js奇怪的鼠标移动行为