JSFiddle - React, Tailwind, and code Playground

by typpo

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<button id="btn-download">
  Download
</button>
<canvas id="chart" width=600 height=600></canvas>

JavaScript

const myChart = new Chart(document.getElementById('chart').getContext("2d"), {
  type: 'horizontalBar',
  data: {
    labels: ['One', 'Two', 'Three', 'Four', 'Five', 'Six'],
    datasets: [{
      label: 'My data',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
      borderColor: 'rgba(255,99,132,1)',
      borderWidth: 1
    }]
  },
  options: {
  	animation: {
    	duration: 1500,
    }
  }
});

// Get the chart's base64 image string
var image = myChart.toBase64Image();
console.log(image);

document.getElementById('btn-download').onclick = function() {
  // Trigger the download
  var a = document.createElement('a');
  a.href = myChart.toBase64Image();
  a.download = 'my_file_name.png';
  a.click();
}