d3 flickering Text on setInterval when update data from csv

时光怂恿深爱的人放手 提交于 2019-12-12 18:42:24

问题


I am new at d3 and learning alot. I have a little problem with updating my data, that i'm getting from a csv file.

I use setInterval() to update the data every second. When it removes and Insert the data again, it flickers for some milliseconds (the table goes away and a new table is generated). What am I doing wrong? How can i get rid of the flicker?

Thanks for Helping! :-)

Here my code:

<script type="text/javascript">
  d3.text("data.csv", function(data) {
    var parsedCSV = d3.csv.parseRows(data);

    var container = d3.select("body")
      .append("table")

    .selectAll("tr")
      .data(parsedCSV).enter()
      .append("tr")

    .selectAll("td")
      .data(function(d) { return d; }).enter()
      .append("td")
      .text(function(d) { return d; });

  });    

  var inter = setInterval(function() {
    updateData();
  }, 1000);    

  function updateData() {
    d3.text("data.csv", function(data) {
      var parsedCSV = d3.csv.parseRows(data);

      var container = d3.select("body")
        .append("table")

      .selectAll("tr")
        .data(parsedCSV).enter()
        .append("tr")

      .selectAll("td")
        .data(function(d) { return d; }).enter()
        .append("td")
        .text(function(d) { return d; });    
    });

    d3.select("body").selectAll("tr")
      .remove()    
  }
</script>

回答1:


Adding transition() to enter/exit/remove calls will resolve your flicker problem.

var circleData = [50, 40, 30, 60, 70];

var svg = d3.select("body").append("svg")
  .attr("width", 500)
  .attr("height", 5000)

var circle = svg.append("circle")
  .attr("cx", 100)
  .attr("cy", 100)
  .attr("r", 25);

setTimeout(function() {
  updateCircles(circleData)
}, 2500)

function updateCircles(data) {

  var circles = svg.selectAll("circle")
    .data(circleData);

  circles.enter()
    .append("circle")
    .attr("cx", 100)
    .attr("cy", function(d, i) {
      return (i + 1) * 100
    })
    .attr("r", 0)
    .attr("fill", 'yellow')
    .transition()
    .duration(1500)
    .attr("r", function(d) {
      return d;
    });

  circles.transition()
    .duration(1500)
    .delay(1500)
    .style('fill', 'green')
    .attr('r', function(d) {
      return d;
    });

  circles.exit()
    .transition().duration(1500).delay(1500)
    .style("fill", "red")
    .transition().duration(1500).delay(3000)
    .attr("r", 0).transition().remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>


来源:https://stackoverflow.com/questions/39765481/d3-flickering-text-on-setinterval-when-update-data-from-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!