Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

前端 未结 7 1964
失恋的感觉
失恋的感觉 2020-11-30 23:57

I am using Chart.js. I am trying to convert the chart to an image by getting a base 64 string. The tutorial (http://www.chartjs.org/docs/) devotes an entire 1 line on the to

相关标签:
7条回答
  • 2020-12-01 00:20

    You can access afterRender hook by using plugins.

    And here are all the plugin api available.

    In html file:

    <html>
      <canvas id="myChart"></canvas>
      <div id="imgWrap"></div>
    </html>
    

    In js file:

    var chart = new Chart(ctx, {
      ...,
      plugins: [{
        afterRender: function () {
          // Do anything you want
          renderIntoImage()
        },
      }],
      ...,
    });
    
    const renderIntoImage = () => {
      const canvas = document.getElementById('myChart')
      const imgWrap = document.getElementById('imgWrap')
      var img = new Image();
      img.src = canvas.toDataURL()
      imgWrap.appendChild(img)
      canvas.style.display = 'none'
    }
    
    0 讨论(0)
提交回复
热议问题