用d3更新圈子不会移动位置?

时间:2018-08-06 07:16:55

标签: d3.js

我尝试按照示例进行操作,但是某些操作没有按预期进行:所有位置都应更新,但只有新添加的点会移动。知道我错过了什么吗?

https://jsfiddle.net/zahachtah/g8jL0fk2/2/

<!DOCTYPE html>
<html>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="chart"></div>
<script>
var svgCont = d3.select("#chart").append("svg")
  .attr("width", 600)
  .attr("height", 600);

var data=[]
for(var i=0; i<10; i++) {
  data.push([(Math.random()*10-5),(Math.random()*10-5)])
}
function update(data) {
  var circles = svgCont.selectAll("circle")
    .data(data)
    .enter()
    .append("circle")
    .attr("cx",  function (d) { return d[0]*5+150;  }) //return Math.rand()*20+300;
    .attr("cy",  function (d) { return d[1]*5+150;  })
    .attr("r",3)
    .style("fill", "green");

  circles.transition()
    .duration(500)
    .attr("cx",  function (d) { return d[0]*5+150+(Math.random()*10-5);  }) //return Math.rand()*20+300;
    .attr("cy",  function (d) { return d[1]*5+150+(Math.random()*10-5);  })
    .attr("r",3)
    .style("fill", "red");

  circles.exit().remove();
};
update(data)

d3.interval(function() {
  data.push([Math.random()*10-5,Math.random()*10-5])
  for(var i=0; i<10; i++) {
    data[i][0]=data[i][0]+(Math.random()*10-5)
    data[i][1]=data[i][1]+(Math.random()*10-5)
  }
  update(data)
  //console.log(data[0])
}, 1500);

</script>

1 个答案:

答案 0 :(得分:-1)

您需要稍微修改更新功能

function update(data) {
  var circles = svgCont.selectAll("circle")
    .data(data);

  circles.enter()
    .append("circle")
    .attr("cx", function(d) {
      return d[0] * 5 + 150;
    }) //return Math.rand()*20+300;
    .attr("cy", function(d) {
      return d[1] * 5 + 150;
    })
    .attr("r", 3)
    .style("fill", "green")

    .merge(circles).transition()
    .duration(500)
    .attr("cx", function(d) {
      return d[0] * 5 + 150 + (Math.random() * 10 - 5);
    }) //return Math.rand()*20+300;
    .attr("cy", function(d) {
      return d[1] * 5 + 150 + (Math.random() * 10 - 5);
    })
    .attr("r", 3)
    .style("fill", "red");

  circles.exit().remove();
};