将仪表板中的 google 图表导出为 png

Export google chart in a dashboard as png

我正在尝试通过按钮将仪表板中的 google 图表导出为 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>

请帮我看看我错在哪里。

一个fiddle总有帮助!

https://jsfiddle.net/kujxsn7z/

我改变的东西:

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

    chart.getChart().getImageURI()

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