React-chartjs-2 Doughnut chart export to png

回眸只為那壹抹淺笑 提交于 2021-01-25 07:09:09

问题


I have created a Doughnut and Bar chart using react-chartjs-2 library. Now I want to export this chart as png i.e the chart gets downloaded as png on user click. I have tried many ways but could not succeed. One of them was to use html2canvas library and get a screenshot but that is degrading the quality of chart. I am wondering is there any function in react-chartjs-2 library to directly export the chart?

Edit- If someone can tell me about any other library in javascript in which I can make the charts like Bar and Doughnut and that library gives me the function to directly export the chart, that would also be helpful.


回答1:


I was able to do it using .toBase64Image() function from react-chartjs-2 library itself.




回答2:


If you are using react-chartjs-2 library, you need to get a ChartJS instance reference and then call .toBase64Image() as the other answer suggested. To do that, first create an empty reference:

const chartRef = useRef(null);

Then, assing the reference. For example, if you are using a Bar chart:

<Bar data={data} ref={chartRef}/>

Finally, get the base64 image using the reference. Remember to call .current.chartInstance before toBase64Image():

const base64Image = chartRef.current.chartInstance.toBase64Image();


来源:https://stackoverflow.com/questions/62039681/react-chartjs-2-doughnut-chart-export-to-png

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!