![]() |
VOOZH | about |
In Chart.js, the charts that are generated can be converted and downloaded as images for easy sharing and reporting. By using built-in methods like toBase64Image() and the HTML canvas toBlob() method, we can enable users to download charts in formats such as PNG. These techniques provide a simple way to capture the visual data from charts and offer a convenient option for exporting and saving graphical content directly from the browser.
Below are the two approaches to downloading Canvas as an Image on Button Click in Chart JS:
Table of Content
You need to add the below link to your HTML document to use Chart.js.
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>In this approach, we are using the toBase64Image() function from Chart.js to convert the pie chart into a base64-encoded image. The button click event creates a temporary anchor element with the href set to the base64 image data, allowing the user to download the chart as a PNG file named pie_chart.png.
Example: The below example uses toBase64Image() function to Download Canvas as Image on Button Click in Chart JS.
Output:
In this approach, we are using the HTML Canvas toBlob() method to convert the chart's canvas to a Blob object, which represents the image data. This Blob is then converted to a URL using URL.createObjectURL(), allowing us to create a download link for the image. Clicking the button triggers this link, enabling the download of the chart as a PNG file.
Example: The below example uses HTML Canvas toBlob() Method to Download Canvas as Image on Button Click in Chart JS.
Output: