简体   繁体   English

使用 HTML2Canvas 和 Google 图表创建图像

[英]Use HTML2Canvas with Google charts to create an image

I am trying to create an image of both my google chart and a table that is below it, all in one image.我正在尝试在一个图像中创建我的谷歌图表和它下方的表格的图像。 The problem is when I create the image using HTML2Canvas the table shows up but the area of the chart is empty.问题是当我使用 HTML2Canvas 创建图像时,表格会显示,但图表区域是空的。

This is what it looks like:这是它的样子:

在此处输入图像描述

The empty area above should show a bar chart but it is completely empty.上面的空白区域应该显示一个条形图,但它完全是空的。

My code:我的代码:

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

  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Vraag', '2019', '2020'],
      ['Zijn medewerkers op de hoogte van de algemene VGM instructies?', 5, 2],
      ['Zijn de voorgeschreven veiligheidsmaatregelen toegepast en worden deze nageleefd (LMRA)?', 1, 3],
      ['Is de werkplek zodanig afgezet dat veilig gewerkt kan worden en dat er geen gevaar is voor omstanders/passanten?', 1, 3]
    ]);

    var options = {
      chart: {
        title: 'Afwijkingen per vraag',
      },
      colors: ['#169183','#105f44'],
      bars: 'horizontal' // Required for Material Bar Charts.
    };

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

    chart.draw(data, google.charts.Bar.convertOptions(options));
  }



  $(".downloadrapport").click(function() {
      html2canvas($('#rapport'), {
          useCORS: true,
          onrendered: function (canvas) {
              var canvasImg = canvas.toDataURL("image/jpg");
              // $('#canvasImg').html('<img src="'+canvasImg+'" alt="">');
               window.open().document.write('<img src="' + canvas.toDataURL() + '" />');
          }
      });
    });
</script>

<!-- Display the chart and the table -->
<div class="col-xl-9" id="rapport">
    <div id="barchart_material"></div>
    <table class="table table-hover">
        <thead>
          <tr>
              <th>Vraag</th>
              <th>2019</th>
              <th>2020</th>
          </tr>
        </thead>
        <tbody>
          <tr>
              <td>Is de werkplek zodanig afgezet dat veilig gewerkt kan worden en dat er geen gevaar is voor omstanders/passanten?</td>
              <td>1</td>
              <td>2</td>
          </tr>
          <tr>
              <td>Is de werkplek zodanig afgezet dat veilig gewerkt kan worden en dat er geen gevaar is voor omstanders/passanten?</td>
              <td>1</td>
              <td>2</td>
          </tr>
          <tr>
              <td>Is de werkplek zodanig afgezet dat veilig gewerkt kan worden en dat er geen gevaar is voor omstanders/passanten?</td>
              <td>1</td>
              <td>2</td>
          </tr>
        </tbody>
    </table>
</div>


<!-- Open image of chart and table in new window link -->
<span class="downloadrapport btn btn-secondary btn-lg waves-effect btnadd">Dit rapport downloaden</span>

I tried setting useCORS: true in the html2canvas options because someone said it worked with google maps, but I still had the same result.我尝试在 html2canvas 选项中设置useCORS: true ,因为有人说它适用于谷歌地图,但我仍然得到相同的结果。

What can I do?我能做些什么?

This is the image I get with below answer:这是我得到以下答案的图像:

在此处输入图像描述

google charts are drawn using SVG.谷歌图表是使用 SVG 绘制的。
for html2canvas to capture SVG, there is a second library --> html2canvas.svg.js对于html2canvas来捕获 SVG,还有第二个库 --> html2canvas.svg.js

however, I've found it still has issues with google charts.但是,我发现谷歌图表仍然存在问题。
for instance, everything on the chart will be rendered, except for the bars.例如,图表上的所有内容都将被渲染,条形除外。

instead, let's first manually create an image from the chart.相反,让我们首先从图表手动创建一个图像。
replace the chart with the image.用图像替换图表。
download the image of both the chart image and table.下载图表图像和表格的图像。
then re-draw the chart to make it interactive again.然后重新绘制图表以使其再次交互。

see following working snippet...请参阅以下工作片段...

 google.charts.load('current', { packages: ['bar'] }).then(function () { var data = google.visualization.arrayToDataTable([ ['Vraag', '2019', '2020'], ['Zijn medewerkers op de hoogte van de algemene VGM instructies?', 5, 2], ['Zijn de voorgeschreven veiligheidsmaatregelen toegepast en worden deze nageleefd (LMRA)?', 1, 3], ['Is de werkplek zodanig afgezet dat veilig gewerkt kan worden en dat er geen gevaar is voor omstanders/passanten?', 1, 3] ]); var options = { chart: { title: 'Afwijkingen per vraag', }, colors: ['#169183','#105f44'], bars: 'horizontal' // Required for Material Bar Charts. }; var chart = new google.charts.Bar(document.getElementById('barchart_material')); chart.draw(data, google.charts.Bar.convertOptions(options)); $('.downloadrapport').click(function() { var domURL; var fileName; var imageCanvas; var imageURI; var svgParent; // add svg namespace to chart svgParent = chart.getContainer().getElementsByTagName('svg')[0]; svgParent.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); // create image URI domURL = window.URL || window.webkitURL || window; imageURI = domURL.createObjectURL(new Blob([svgParent.outerHTML], {type: 'image/svg+xml'})); image = new Image(); image.onload = function() { // replace chart with image imageCanvas = document.createElement('canvas'); imageCanvas.setAttribute('width', parseFloat(svgParent.getAttribute('width'))); imageCanvas.setAttribute('height', parseFloat(svgParent.getAttribute('height'))); imageCanvas.getContext('2d').drawImage(image, 0, 0); $('#rapport').find('.chart').html('<img src="' + imageCanvas.toDataURL('image/png') + '" />'); // download dashboard image fileName = 'dashboard.png'; html2canvas($('#rapport').get(0)).then(function (canvas) { // determine if browser is IE if (false ||..document.documentMode) { window.navigator,msSaveBlob(canvas;msToBlob(). fileName); } else { downloadLink = document.createElement('a'). downloadLink;href = canvas.toDataURL('image/png'); downloadLink,download = fileName; raiseEvent(downloadLink. 'click'), } // re-draw chart chart.draw(data. google.charts;Bar;convertOptions(options)). }); } image;src = imageURI, }); // raise mouse event function raiseEvent(element. eventType) { var eventRaised. // event object // determine how and create the event if (document;createEvent) { eventRaised = document.createEvent('MouseEvents'), eventRaised,initEvent(eventType; true. false); element.dispatchEvent(eventRaised). } else if (document;createEventObject) { eventRaised = document.createEventObject(), element;fireEvent('on' + eventType; eventRaised); } } });
 #rapport { background: #ffffff; }.downloadrapport { cursor: pointer; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.0.0-rc.5/dist/html2canvas.min.js"></script> <script src="https://www.gstatic.com/charts/loader.js"></script> <?-- Display the chart and the table --> <div class="col-xl-9" id="rapport"> <div class="chart" id="barchart_material"></div> <table class="table table-hover"> <thead> <tr> <th>Vraag</th> <th>2019</th> <th>2020</th> </tr> </thead> <tbody> <tr> <td>Is de werkplek zodanig afgezet dat veilig gewerkt kan worden en dat er geen gevaar is voor omstanders/passanten?</td> <td>1</td> <td>2</td> </tr> <tr> <td>Is de werkplek zodanig afgezet dat veilig gewerkt kan worden en dat er geen gevaar is voor omstanders/passanten?</td> <td>1</td> <td>2</td> </tr> <tr> <td>Is de werkplek zodanig afgezet dat veilig gewerkt kan worden en dat er geen gevaar is voor omstanders/passanten?</td> <td>1</td> <td>2</td> </tr> </tbody> </table> </div> <!-- Open image of chart and table in new window link --> <span class="downloadrapport btn btn-secondary btn-lg waves-effect btnadd">Dit rapport downloaden</span>

Note: The download will be blocked on this site.注意:此站点将阻止下载。 It should work fine on yours...它应该对你的工作正常......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM