Open In App

How to Download Canvas as Image on Button Click in ChartJS?

Last Updated : 30 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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:

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>

Using toBase64Image() function

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.

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Using to Base64Image() function </title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
        }

        h1 {
            color: green;
        }

        h3 {
            margin-top: 0;
        }

        canvas {
            max-width: 100%;
            height: auto;
        }

        .container {
            max-width: 400px;
            margin: 0 auto;
        }

        .chart-container {
            position: relative;
            width: 300px;
            height: 300px;
            margin: 0 auto;
        }

        .button-container {
            text-align: center;
            margin-top: 10px;
        }

        .button-container button {
            padding: 10px 20px;
            font-size: 14px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>GeeksforGeeks</h1>
        <h3>Using toBase64Image() function</h3>
        <div class="chart-container">
            <canvas id="myPieChart"></canvas>
        </div>
        <div class="button-container">
            <button id="downloadBtn">
                Download as Image
            </button>
        </div>
    </div>

    <script src=
"https://cdn.jsdelivr.net/npm/chart.js">
   </script>
    <script>
        // Initialize Chart.js Pie Chart
        const ctx = document.getElementById('myPieChart')
            .getContext('2d');
        const myPieChart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: ['Red', 'Blue', 'Yellow'],
                datasets: [{
                    label: 'GeeksforGeeks Data',
                    data: [10, 20, 30],
                    backgroundColor: ['red', 'blue', 'yellow'],
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });

        // Download button functionality
        document.getElementById('downloadBtn')
            .addEventListener('click', () => {
                const image = myPieChart
                    .toBase64Image();
                const link = document
                    .createElement('a');
                link.href = image;
                link.download = 'pie_chart.png';
                link.click();
            });
    </script>
</body>

</html>

Output:

Using HTML Canvas toBlob() Method

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.

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Using HTML Canvas toBlob() Method </title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
        }

        h1 {
            color: green;
        }

        h3 {
            margin-top: 0;
        }

        canvas {
            max-width: 100%;
            height: auto;
        }

        .container {
            max-width: 400px;
            margin: 0 auto;
        }

        .chart-container {
            position: relative;
            width: 300px;
            height: 300px;
            margin: 0 auto;
        }

        .button-container {
            text-align: center;
            margin-top: 10px;
        }

        .button-container button {
            padding: 10px 20px;
            font-size: 14px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>GeeksforGeeks</h1>
        <h3>Using HTML
            Canvas `toBlob()` Method
        </h3>
        <div class="chart-container">
            <canvas id="myBarChart"></canvas>
        </div>
        <div class="button-container">
            <button id="downloadBtn">Download
                as Image
            </button>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js">

    </script>
    <script>
        // Initialize Chart.js Bar Chart
        const ctx = document
            .getElementById('myBarChart')
            .getContext('2d');
        const myBarChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['HTML', 'CSS', 'JavaScript', 'Python'],
                datasets: [{
                    label: 'GeeksforGeeks Tutorials',
                    data: [30, 50, 70, 40],
                    backgroundColor: ['red', 'blue', 'green', 'purple']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });

        // Download button functionality using Canvas toBlob() method
        document.getElementById('downloadBtn')
            .addEventListener('click', () => {
                const canvas = document
                    .getElementById('myBarChart');
                canvas.toBlob((blob) => {
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = 'bar_chart.png';
                    link.click();
                });
            });
    </script>
</body>

</html>

Output:


Next Article

Similar Reads