javascriptchartschart.jschartjs-2.6.0

Render Chartjs on hidden DIV


I'm trying to render many charts using chart.js on a hidden div, then convert them to images to use in a PDF report.

My problem is: if the chart is not rendered on the DOM, I can't capture it and draw it on a canvas. Until the chart is shown, it doesn't render. I've tried to use the methods of draw and render from chart.js but they don't produce the desired results.

Here's my example HTML:

<div style="display: none;">
  <canvas id="myChart"></canvas>
</div>

And my corresponding JavaScript:

var canvas: any = document.getElementById('myChart');
var ctx: any = canvas.getContext('2d');
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',
    // The data for our dataset
    data: {
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
      datasets: [{
            label: 'My First dataset',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
          }]
        },

        // Configuration options go here
        options: {}
      });

for (var id in Chart.instances) {
    Chart.instances[id].resize();
    Chart.instances[id].draw('1s');
    Chart.instances[id].render('1s');
    console.log(Chart.instances[id].toBase64Image());
}

Is there any way to manually render the chart without displaying it, then capture the output as an image?


Solution

  • The fastest hack would be to replace:

    <div style="display: none;">
    

    with

    <div style="position:absolute;left:-9999px;top:-9999px;">
    

    and it will work: https://jsfiddle.net/FGRibreau/n1cx9d70/2/ :)

    PS: If you need to render the chart server-side (e.g. in a batch) in order to then embed it inside PDF reports then you might want to consider dedicated services like Image-Charts.