[Chartjs]-Can you draw a graph without rendering it?

1๐Ÿ‘

โœ…

I found a similair thread to this, only change that was needed to his example was telling chartjs to not animate the chart. Then you can render it out of the screen in a div. You will have to make the div big enough so your chart is also large enough that you can use it.

Original thread: Render Chartjs on hidden DIV

var canvas = document.getElementById('myChart');
var ctx = 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]
          }]
        },

        options: {
        animation: {
        duration: 0
        }
        }
      });

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());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>

<div style="position:absolute;left:-9999px;top:-9999px">
  <canvas id="myChart"></canvas>
</div>

Leave a comment