4

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?

Dean
  • 2,084
  • 17
  • 23
Paulo Galdo Sandoval
  • 2,173
  • 6
  • 27
  • 44
  • What does this have to do with Angular exactly? – Dean Feb 06 '20 at 04:13
  • @Dean my bad, wrong tag, it's coded on angular but it doesn't applies, fixing now – Paulo Galdo Sandoval Feb 06 '20 at 04:15
  • What, specifically, is happening? Are you getting an error? Is the image appearing but garbled? Take a look at [this answer](https://stackoverflow.com/questions/20206038/converting-chart-js-canvas-chart-to-image-using-todataurl-results-in-blank-im). Also off the top of my head, you could probably render it on a canvass that is visible but not in the viewport. – Dean Feb 06 '20 at 04:30
  • @Dean the canvas used to render the chart is always on height and width in 0, and when i try to get the base64 value from the chart is blank – Paulo Galdo Sandoval Feb 06 '20 at 04:31

1 Answers1

4

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.

James Lawruk
  • 30,112
  • 19
  • 130
  • 137
FGRibreau
  • 7,021
  • 2
  • 39
  • 48