如何在不重绘每一帧的情况下更新d3可视化?

时间:2016-10-06 04:20:36

标签: javascript d3.js svg

我正在使用d3创建波形可视化。我看起来很棒,但是在设计这个波形的努力中,我并没有注意以优化的方式做到这一点;我只是想让它发挥作用。

setInterval(function() {
  if (refresh) waveform();
  if (palette_refresh) {
    palette_refresh = false;
    updateColorPalette();
  }
}, options.refresh_rate);

function waveform() {
  analyser.getByteFrequencyData(fd);
  document.getElementById('wf_box').innerHTML = "";

  var data = ... irrelevant implementation details ...

  var chart = d3.select("#wf_box").append("svg")
    .attr("class", "chart")
    .attr("width", "" + percent_offset + "%")
    .attr("style", "padding-left:" + (100 - percent_offset) + "%;")
    .attr("viewBox", "0 0 " + Math.max(w * data.length, 0) + " " + Math.max(h, 0));

  chart.selectAll("rect")
    .data(data)
    .enter().append("rect")
    .attr("x", function(d, i) {
      var x_offset = x(i) - Math.max(w * max / 900 - 0.25, 0.1) / 2;
      return x_offset;
    })
    .attr("y", function(d, i) {
      var height = y(d * options.bar_height) / h;
      return h - Math.pow(Math.max(height, 0.01), 1.5);
    })
    .attr("width", function(d) {
      return '1px';
    })
    .attr("height", function(d, i) {
      var height = y(d * options.bar_height) / h;
      return Math.pow(Math.max(height, 0.01), 1.5) + options.bar_y_offset;
    });
}

如您所见,我使用options.refresh_rate作为我的速度重复调用波形函数。我想,有一种更有效的方法来更新波形中使用的数据,而不是从DOM中删除波形并重新绘制每帧。有没有人对我如何做到这一点有任何见解?

谢谢!

1 个答案:

答案 0 :(得分:0)

在d3 https://bl.ocks.org/mbostock/3808218中查看输入/退出/更新模式,看看是否可以提示。