How to add image inside the doughnut chart using chart.js?

by arnoldo.moen , in category: Javascript , 4 months ago

How to add image inside the doughnut chart using chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 4 months ago

@arnoldo.moen 

To add an image inside a doughnut chart using Chart.js, you can use a custom plugin. You'll need to follow these steps:

  1. Firstly, include the Chart.js library in your HTML file.
1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


  1. Next, create a new canvas element in your HTML where the chart will be rendered.
1
<canvas id="myChart"></canvas>


  1. Create a custom plugin named "chartImage" which will handle adding the image inside the doughnut chart.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Chart.plugins.register({
    afterDraw: function(chart) {
        if (chart.config.options.chartImage) {
            var chartArea = chart.chartArea;
            var ctx = chart.ctx;
            var img = new Image();
            img.src = chart.config.options.chartImage;
            ctx.drawImage(img, chartArea.left, chartArea.top, chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
        }
    }
});


  1. Initialize the doughnut chart with the custom "chartImage" plugin and provide the image URL.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: ['Red', 'Blue', 'Yellow'],
        datasets: [{
            data: [20, 30, 50],
            backgroundColor: ['red', 'blue', 'yellow']
        }]
    },
    options: {
        chartImage: 'image.jpg' // Provide the image URL here
    }
});


Make sure to replace "image.jpg" with the actual URL of your image.


That's it! The image specified in the chartImage option will now be added inside the doughnut chart.