避免重新绘制图表,D3

时间:2018-02-09 23:44:24

标签: javascript reactjs d3.js charts nvd3.js

首次安装组件时,我正在NVD3中使用React库绘制散点图。我隐藏并显示组件,具体取决于单击的按钮。每次组件出现时,它都会被挂载,所以它被重新绘制但是我想避免重绘,对图表进行某种缓存,因为绘制带有许多数据点的图表需要相当多的时间。我在createScatterChart中致电componentDidMount

createScatterChart() {
  const node = this.node
  nv.utils.symbolMap.set('thin-x', function(size) {
    size = Math.sqrt(size);
    return 'M' + (-size/2) + ',' + (-size/2) +
            'l' + size + ',' + size +
            'm0,' + -(size) +
            'l' + (-size) + ',' + size;
  });
// create the chart
  var chart;
  nv.addGraph(function() {
    chart = nv.models.scatterChart()
        .showDistX(true)
        .showDistY(true)
        .useVoronoi(true)
        .color(d3.scale.category10().range())
        .duration(300)
    ;
    var data_func = () => this.props.datum;
    var data_obj = data_func();
    var that = this;
    chart.tooltip.contentGenerator(function (d) {
      //var html = "<div>";
      var html = "";
      d.series.forEach(function(elem){
        Object.keys(data_obj).forEach(function(key_1) {
          var outer_obj = data_obj[key_1];
          if (outer_obj["key"] === elem.key) {
              that.showBarChart(elem.key);
              html += "<p>cluster " + elem.key + "</p>";
              /*var expr = outer_obj["values"][0]["expr"];
              html += "<p>" + elem.key + "</p>";
              html += "<p>x = " + d.value + ", y = " + elem.value + "</p>";*/
          }
        });
      })
      //html += "</div>";
      return html;
    });

    chart.dispatch.on('renderEnd', function(){
        console.log('render complete');
    });

    chart.xAxis.tickFormat(d3.format('.02f'));
    chart.yAxis.tickFormat(d3.format('.02f'));

    d3.select(node)
        .datum(data_func)
        .call(chart);

    nv.utils.windowResize(chart.update);
    chart.dispatch.on('stateChange', function(e) { ('New State:', JSON.stringify(e)); });
    return chart;
}.bind(this));
}

函数最终返回chart,所以我能以某种方式将其保存在变量中然后以更快的速度绘制它吗?或者你会建议如何缓存图表?

1 个答案:

答案 0 :(得分:1)

可以通过更改html元素的visible属性而不是渲染它来解决问题。

<div visibility={this.state.showButton ? "visible": "hidden"} ></div>