Open In App

How to Converte Chart.js Canvas Chart to Image using .toDataUrl() Results in Blank Image?

Last Updated : 28 Aug, 2024
Comments
Improve
Suggest changes
1 Likes
Like
Report

In Chart.js, we can convert the canvas chart into an image using the .toDataURL() method, which generates a base64-encoded data URL representing the chart. This allows us to save or display the chart as an image.

These are the following approaches:

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>

Basic Conversion to Image

In this approach, we are using Chart.js to create a bar chart that is displayed alongside a button. When the button is clicked, the chart is converted to an image using the toDataURL() method, which generates a base64-encoded image from the chart's canvas element. This image is then displayed in an <img> tag beside the chart.

Example: The below example performs Basic Conversion to Image.

HTML
<!DOCTYPE html>
<html>

<head>

    <title>Convert Chart.js Canvas to Image</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }

        h3 {
            margin-top: 0;
            text-align: center;
        }

        .container {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .chart-container {
            position: relative;
            width: 300px;
            height: 300px;
            margin-right: 20px;
        }

        .image-container {
            width: 300px;
            height: 300px;
        }

        .image-container img {
            width: 100%;
            height: auto;
        }

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

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

<body>
    <h3>Basic Conversion to Image</h3>
    <div class="button-container">
        <button id="generateImageBtn">Generate Image</button>
    </div>
    <div class="container">
        <div class="chart-container">
            <canvas id="chart1"></canvas>
        </div>
        <div class="image-container">
            <img id="chartImage1" src="" alt="Chart Image">
        </div>
    </div>

    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
    <script>
        // Create the chart
        const ctx1 = document.getElementById('chart1').getContext('2d');
        const chart1 = new Chart(ctx1, {
            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
            },
            plugins: [{
                id: 'chartRendered',
                afterRender: function (chart, options) {
                    document.getElementById('generateImageBtn').disabled = false;
                }
            }]
        });

        // Convert chart to image using toDataURL
        document.getElementById('generateImageBtn')
                .addEventListener('click', function () {
            const chartCanvas = document.getElementById('chart1');
            const chartImage = document.getElementById('chartImage1');
            const imageDataURL = chartCanvas.toDataURL('image/png');
            chartImage.src = imageDataURL;
        });
    </script>
</body>

</html>

Output:

Advanced Conversion with Custom Image Styling

In this approach, we are enhancing the conversion of a Chart.js canvas chart to an image by applying advanced styling and layout adjustments. The .toDataURL() method is used to convert the chart into a base64-encoded image, which is then displayed within a styled container with custom borders, shadows, and hover effects.

Example: The below example performs Advanced Conversion with Custom Image Styling.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0">
    <title>Convert Chart.js Canvas to Image</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        h3 {
            margin-top: 0;
            text-align: center;
            font-size: 1.5rem;
            color: #333;
        }

        .container {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-wrap: wrap;
            margin-top: 20px;
            gap: 20px;
        }

        .chart-container {
            position: relative;
            width: 350px;
            height: 350px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            background: #fff;
        }

        .image-container {
            width: 350px;
            height: 350px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2px solid #ddd;
            border-radius: 8px;
            background: #fff;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        .image-container img {
            width: 100%;
            height: auto;
            border: 3px solid green;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

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

        .button-container button {
            padding: 12px 24px;
            font-size: 16px;
            background-color: green;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease, transform 0.3s ease;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        .button-container button:hover {
            background-color: darkgreen;
            transform: scale(1.05);
        }

        @media (max-width: 768px) {

            .chart-container,
            .image-container {
                width: 100%;
                height: 300px;
            }
        }
    </style>
</head>

<body>
    <h3>Advanced Conversion with Custom Image Styling</h3>
    <div class="container">
        <div class="chart-container">
            <canvas id="chart2"></canvas>
        </div>
        <div class="image-container">
            <img id="chartImage2" src="" alt="Chart Image">
        </div>
    </div>
    <div class="button-container">
        <button onclick="convertToImage()">Generate Image</button>
    </div>

    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
    <script>
        const ctx2 = document.getElementById('chart2').getContext('2d');
        const chart2 = new Chart(ctx2, {
            type: 'bar',
            data: {
                labels: ['Java', 'C#', 'Ruby', 'PHP'],
                datasets: [{
                    label: 'GeeksforGeeks Programming Languages',
                    data: [45, 60, 30, 70],
                    backgroundColor: ['blue', 'green', 'red', 'orange']
                }]
            },
            options: {
                responsive: true
            }
        });

        function convertToImage() {
            const image = document.getElementById('chartImage2');
            image.src = document.getElementById('chart2').toDataURL('image/png');
        }
    </script>
</body>

</html>

Output:


Explore