如何在另一个 div 中克隆并重新绘制 google 图表?

how to clone and re draw google chart in another div?

我很难弄清楚如何做到这一点,因为我对 google 图表不太熟悉。

我正在使用 pivotTable.js 并且一切正常,但我想要 "save" 或者有一个按钮可以将当前创建的图表克隆到另一个 div。

我做了一个全局变量

var wrapper;

这是为了保存图表

 wrapper = new google.visualization.ChartWrapper({
      dataTable: dataTable,
      chartType: chartType,
      options: options
    });
    wrapper.draw(result[0]);

在此之后,当单击按钮时包装图表,应该在另一个 div 中重绘。

<div id="trial" style="margin: 30px;"></div>

我尝试这样做,但我知道如何将图表放入试用版 div。

  // Never called.
      google.visualization.events.addListener(wrapper, 'onmouseover', uselessHandler);


      google.visualization.events.addListener(wrapper, 'ready', onReady);


      // Never called
      function uselessHandler() {
        alert("I am never called!");
      }

      function onReady() {
        google.visualization.events.addListener(wrapper.getChart(), 'click', usefulHandler);
      }

      // Called
      function usefulHandler() {
        alert(wrapper.getChart());
      }

已解决:

   function getChart() {
  google.visualization.events.addListener(wrapper, 'ready', onReady);
      function onReady() {
        google.visualization.events.addListener(wrapper.getChart(), 'click', usefulHandler);
      }
    var trialChart = wrapper.clone();
    trialChart.setContainerId('trial');
    trialChart.draw();
}

after clone() -- 只需要设置新的 containerId

请参阅以下工作片段...

google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable();
    data.addColumn('date', 'Date');
    data.addColumn('number', '2015');
    data.addColumn('number', '2016');
    data.addRows([
       [new Date('01/01/2016'), 200, 210],
       [new Date('01/02/2016'), 190, 220],
       [new Date('01/03/2016'), 205, 200],
       [new Date('01/04/2016'), 220, 230],
       [new Date('01/05/2016'), 212, 210],
       [new Date('01/06/2016'), 185, 193],
       [new Date('01/07/2016'), 196, 207]
    ]);

    var chart = new google.visualization.ChartWrapper({
      chartType: 'LineChart',
      containerId: 'chart_orig',
      dataTable: data,
      options: {
        height: 400
      }
    });

    google.visualization.events.addOneTimeListener(chart, 'ready', function () {
      document.getElementById('cloneBtn').addEventListener('click', function () {
        var trialChart = chart.clone();
        trialChart.setContainerId('chart_trial');
        trialChart.draw();
      }, false);
    });

    chart.draw();
  },
  packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<input type="button" id="cloneBtn" value="Clone" />
<div>Original Chart</div>
<div id="chart_orig"></div>
<div>Trial Chart</div>
<div id="chart_trial"></div>