I was working on a tool where I needed to show Chart.js chart as image. I’m going to share a snippet to show I achieved it.
Chart.js have an afterRender() callback function which is called after a chart has been completely rendered, including the animation. Because there is no option given in Chart.js to show a chart as an image, I used that callback function to convert the canvas into an image.
Chart.js have an API method – toBase64Image() which returns a chart as a base 64 encoded string. I used this method inside the afterRender() callback function.
Now, First we create a simple canvas.
<canvas id="mychart"></canvas>
Now we apply the javascript.
new Chart("mychart", {
type: 'bar',
data: {
labels: ["06-2020", "07-2020", "08-2020", "09-2020", "10-2020", "11-2020", "12-2020", "01-2021", "02-2021", "03-2021", "04-2021", "05-2021"],
datasets: [{
label: '# of Sells',
data: [12, 19, 30, 17, 12, 26, 20, 13, 15, 16, 20, 10],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
plugins: [{
afterRender: function (chart, args, options) {
var img = new Image();
img.src = chart.toBase64Image('image/png', 1);
chart.canvas.parentNode.insertBefore(img, chart.canvas.nextSibling);
chart.canvas.style.display = 'none'; // Hide the chart canvas
chart.canvas.remove(); // To remove the chart canvas
}
}]
});
Thanks a lot for this article! It is the first up to date in this topic, from chart.js 3.0+ there is some breaking changes in the related functions