[Chartjs]-Converting the chartjs charts into base64

1👍

I think a good approach would be to convert the canvas into an image (toDataURL()) and then proceed with that.

With css media queries (@media screen / @media print) you can control the appearance. (commented out in the snippet)

const months = [1, 2, 3]
const ndvi_data = [3, 4, 5]
const evi_data = [6, 7, 8, 9]
new Chart(document.getElementById("ndvi_evi_chart"), {
  type: 'bar',
  data: {
    labels: months,
    datasets: [{
      label: "NDVI",
      type: "bar",
      stack: "Base",
      backgroundColor: "#6418C3",
      data: ndvi_data,
    }, {
      label: "EVI",
      type: "bar",
      stack: "Sensitivity",
      backgroundColor: "#B270ED",
      data: evi_data,
    }]
  },

  options: {
    plugins: {
      legend: {
        display: true,
        position: "top",
        align: "end"
      }
    },

    scales: {
      xAxes: [{
        //stacked: true,
        stacked: true,
        ticks: {
          beginAtZero: true,
          maxRotation: 0,
          minRotation: 0
        }
      }],
      yAxes: [{
        stacked: true,
        scaleLabel: {
          display: true,
          labelString: 'NDVI and EVI'
        },
      }]
    },

    animation: {
      onComplete: function() {
        const img = document.getElementById('ndvi_evi_chart').toDataURL('image/png')
        document.getElementById('canvas-as-image').innerHTML = '<img src="' + img + '">'
      }
    }

  },

});
.chartNdvi {
  width: 500px;
  padding: 20px;
  background: white;
}


/*
@media screen {
  #ndvi_evi_chart {
    display: block;
  }
  #canvas-as-image {
    display: none;
  }
}

@media print {
  #ndvi_evi_chart {
    display: none;
  }
  #canvas-as-image {
    display: block;
  }
}
*/
<div class="chartNdvi" style="border:1px solid #A9A9A9">
  <p style="font-weight: bold; font-size:15px;">Crop Health</p>
  <p style="font-size:10px;">NDVI and EVI (Six Month Historical Data)</p>
  <canvas id="ndvi_evi_chart" width="200" height="80"></canvas>
  <div id="canvas-as-image"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.3.2/dist/chart.min.js"></script>

Leave a comment