I'm trying to download my chart.js charts as png using a button Onclick, but I have no idea how I'm going to achieve this , I've went through this answer React-chartjs-2 Doughnut chart export to png but it wasn't quite clear enough for me as I'm quite new in chart.js don't know how I'm going to connect those variables with my button.
import React from 'react';
import { Component, useRef } from 'react';
import { Bar } from 'react-chartjs-2';
import 'chartjs-plugin-datalabels';
const data = {
labels: ['Finance & Business', 'Mining', 'Community Services', 'Electricity', 'Agriculture', 'Construction', 'Manufacture', "Trade & Tourism", "Transport & Logistics"],
datasets: [
{
label: 'My First dataset',
backgroundColor: ["#3283FC", "", "", "#00C0C8", "#C0BD00", "#3A46B1", "#00A150", "#FEB200", "#9302a1"],
borderWidth: 1,
hoverBackgroundColor: 'rgba(255,99,132,0.4)',
hoverBorderColor: 'rgba(255,99,132,1)',
data: [0.6, 0.0, 0.0, -0.1, -0.1, -0.3, -0.3, -0.6, -1.0],
}
]
};
class StackedBar extends Component {
render() {
return (
<div>
<h2>Bar Example (custom size)</h2>
<Bar
data={data}
options={{
plugins: {
datalabels: {
display: true,
color: '#fff'
}
},
title: {
display: true,
text: 'Contribution Percentage',
position: 'left'
},
maintainAspectRatio: true,
scales: {
xAxes: [{
stacked: true,
gridLines: {
borderDash: [2, 6],
color: "black"
},
scales: {
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
steps: 0.5,
stepSize: 0.5,
max: 1.5,
min: -1.0
},
}]
},
}}
/>
</div>
);
}
}
export default StackedBar;
So I installed a plugin called FileSave.js //
npm i file-saver
import { saveAs } from 'file-saver';