将仪表板中的谷歌图表导出为png

时间:2015-06-01 05:48:33

标签: charts google-visualization dashboard

我正在尝试将仪表板中的谷歌图表导出为通过按钮png图像。但是我收到以下错误 -

一个或多个参与者未能绘制() undefined不是函数

以下是代码:

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">

      // Load the Visualization API and the controls package.
      google.load('visualization', '1.0', {'packages':['controls']});

      // Set a callback to run when the Google Visualization API is loaded.
      google.setOnLoadCallback(drawDashboard);

      // Callback that creates and populates a data table,
      // instantiates a dashboard, a range slider and a pie chart,
      // passes in the data and draws it.
      function drawDashboard() {

        // Create our data table.
        var data = google.visualization.arrayToDataTable([
          ['Name', 'Donuts eaten'],
          ['Michael' , 5],
          ['Elisa', 7],
          ['Robert', 3],
          ['John', 2],
          ['Jessica', 6],
          ['Aaron', 1],
          ['Margareth', 8]
        ]);



        // Create a dashboard.
        var dashboard = new google.visualization.Dashboard(
            document.getElementById('dashboard_div'));

        // Create a range slider, passing some options
        var select = new google.visualization.ControlWrapper({
          'controlType': 'CategoryFilter',
          'containerId': 'filter_div',
          'options': {
            'filterColumnLabel': 'Donuts eaten'
          }
        });

        // Create a pie chart, passing some options
        var chart = new google.visualization.ChartWrapper({
          'chartType': 'ColumnChart',
          'containerId': 'chart_div',
          'options': {
            'width': 500,
            'height': 300,
            'legend': 'right'
          }
        });

        google.visualization.events.addListener(chart, 'ready', function(e) {
                document.getElementById('png').outerHTML = '<a href="' + chart.getImageURI() + '">Printable version</a>';
        });

        // Establish dependencies, declaring that 'filter' drives 'pieChart',
        // so that the pie chart will only display entries that are let through
        // given the chosen slider range.
        dashboard.bind(select, chart);

        // Draw the dashboard.
        dashboard.draw(data);
      }
    </script>
  </head>

  <body>
    <div id='png'></div>
    <!--Div that will hold the dashboard-->
    <div id="dashboard_div">        
      <!--Divs that will hold each control and chart-->
      <div id="filter_div"></div>
      <div id="chart_div"></div>
    </div>
  </body>
</html>

请在我出错的地方帮助我。

1 个答案:

答案 0 :(得分:5)

小提琴总是有帮助!

https://jsfiddle.net/kujxsn7z/

我改变的事情:

  • 创建了一个div来保存PNG输出您试图调用
  • getImageURI()失败了,因为你在它上面应用了它 chartWrapper,不在图表对象上。所以要解决这个问题,你需要打电话, 在你的实例中:

    chart.getChart().getImageURI()

所以你引用你的chartWrapper,使用getChart来引用它包含的图表,然后在图表对象本身上执行getImageIRI()。