我想在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);
&#13;
<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>
&#13;
答案 0 :(得分:2)
你只有输入模式。要重新绘制,您需要调用更新模式,另请参阅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');
}
您的问题的工作示例是here。