在html中生成图形并另存为图像

时间:2017-05-15 06:30:37

标签: javascript html html2canvas

我想使用某些值生成图形,并将输出捕获/保存为jpeg / png。我正在使用谷歌图表生成图表并使用html2canvas捕获。以下是我正在尝试的代码。

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="html2canvas.js"></script>

    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <script language="javascript">

    <script type="text/javascript">
      google.charts.load('current', {'packages':['bar']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses', 'Profit'],
          ['2014', 1000, 400, 200],
          ['2015', 1170, 460, 250],
          ['2016', 660, 1120, 300],
          ['2017', 1030, 540, 350]
        ]);

        var options = {
          chart: {
            title: 'Company Performance',
            subtitle: 'Sales, Expenses, and Profit: 2014-2017',
          },
          bars: 'horizontal' 
        };

        var chart = new google.charts.Bar(document.getElementById('barchart_material'));

        chart.draw(data, google.charts.Bar.convertOptions(options));
      }
    $(document).ready(function() {
    html2canvas($("#barchart_material"), {
        onrendered: function(canvas) {
            // canvas is the final rendered <canvas> element
            var myImage = canvas.toDataURL("image/png");
            window.open(myImage);
        }
    });
</script>
  </head>
  <body>
<div id="barchart_material" style="width: 900px; height: 500px;"></div>
</body>
</html>

谷歌图形工作正常,并且捕获的图像打开,作为单独的代码,但当我合并两者时它没有。 而且,我的目标是在本地保存图像而不仅仅是打开图像。

1 个答案:

答案 0 :(得分:1)

为自己省去了很多麻烦,并且没有使用互动式Google Charts API。请改用基于图像的图表。

https://developers.google.com/chart/image/docs/gallery/bar_charts