为什么这个 d3 示例中的圆圈不移动

Why don't the circles in this d3 example move?

本文关键字:移动 d3 为什么      更新时间:2023-09-26

我想在 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');
}

您的问题的工作示例在这里。