javascriptchartschart.jshtml2canvastodataurl

html2canvas Chart.js chart not rendered


I am trying to export a div that contains a Chart.js chart as an Iamge. All elements are displayed perfectly fine, however, the Chart.js canvas just doesn't get rendered.

I am calling my export function in the callback of the onAnimationComplete option in my chart, so the export can't happen before the chart is fully built.

Here is how my html2canvas and download functions look:

download() {
        this.dl.download = this.fileName;
        this.dl.click();
}

loadDataUrl($node) {
    this.hideUnwantedElements();
    html2canvas($node, {
        background: '#ffffff',
        scale: 4,
        proxy: 'proxy-for-cors-images',
        onrendered: (canvas) => {
            this.showElements();
            this.dl.href = canvas.toDataURL('image/jpeg');
        }});
}

Can anyone tell me if it is even possible to export Chart.js charts with html2canvas and if so, how? I also tried the toDataURL() function on the chart canvas but it only returns the data URL for a tranparent png.


Solution

  • Yes! It is possible to export (save as image) chart (created with ChartJS) using html2canvas.

    HERE IS HOW :

    var isChartRendered = false;
    
    var chart = new Chart(ctx, {
       type: 'line',
       data: {
          labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
          datasets: [{
             label: 'LINE',
             data: [3, 1, 4, 2, 5],
             backgroundColor: 'rgba(0, 119, 290, 0.2)',
             borderColor: 'rgba(0, 119, 290, 0.6)',
             fill: false
          }]
       },
       options: {
          // setting following option is mandatory
          animation: {
             onComplete: function() {
                isChartRendered = true
             }
          }
       }
    });
    
    function download() {
       if (!isChartRendered) return; // return if chart not rendered
       html2canvas(document.getElementById('chart-container'), {
          onrendered: function(canvas) {
             var link = document.createElement('a');
             link.href = canvas.toDataURL('image/jpeg');
             link.download = 'myChart.jpeg';
             link.click();
          }
       })
    }
    #chart-container { background: white }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
    <button onclick="download()">save chart as...</button>
    <div id="chart-container">
       <canvas id="ctx"></canvas>
    </div>

    PS: Needless to say but obviously, this is just an example, you need to adopt this accordingly to your project.