使用HTML2Canvas与Google图表一起创建图像。

问题描述 投票:1回答:1

我正试图创建一个我的谷歌图表和它下面的一个表格的图像,所有的图像。问题是,当我使用HTML2Canvas创建图像时,表格显示出来,但图表的区域是空的。

这就是它的样子。

enter image description here

上面的空白区域应该显示一个条形图 但它完全是空的。

我的代码。

<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>

我试着设置了 useCORS: true 的 html2canvas 选项中,因为有人说它可以与 google 地图一起使用,但我的结果还是一样。

我可以做什么?

这是我得到的图像与下面的答案。

enter image description here

javascript jquery charts google-visualization bar-chart
1个回答
1
投票

google图表是使用SVG绘制的。html2canvas 捕捉SVG,有第二个库--&gt.然而,我发现它在谷歌图表上还是有问题。html2canvas.svg.js

然而,我发现它在google图表上仍然存在问题.例如,图表上的一切都会被渲染,除了条形图。

相反,让我们先从图表中手动创建一个图像,用图像替换图表,下载图表图像和表格的图像,然后重新绘制图表,使其再次互动。

请看下面的工作片段...

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/[email protected]/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>

注意:在这个网站上下载将被阻止。在你的网站上应该可以正常工作...

© www.soinside.com 2019 - 2024. All rights reserved.