Chartjs-How to apply image on each bubble in chartjs?

0👍

You can, but not with the result you might expect.

If you set the pointStyle property to an image like so:

myImage = new Image()
myImage.src = 'img/image.png';

...

const data = {
    labels: [...],
    datasets: [
        {
            label: 'Something',
            data: [...your data...],
            pointStyle: myImage,     ///// SET IMAGE FOR BUBBLE
        }
    ]

}

The size of the image however is no longer determined by the bubble radius r. So as far as I can tell it’s not currently possible unless you come up with a way to manage the size of the image in relation to r by your self.

0👍

You can do it by using chartjs-plugin. Add chartjs-plugin.js in your project and use the following code to add an image on each bubble.

The following code will add a specific image on each bubble.

var icon = new Image();
icon.src = baseURL + "assets/user/images/mood_trend_sad_icon.png";
icon.width = 22;
icon.height = 22;

new Chart(chartCanvas, {
    type: 'bubble',
    data: chartData,
    options: chartOptions,
    plugins: [{
        afterUpdate: function (chart, options) {
            chart.getDatasetMeta(0).data.forEach((d, i) => {
                d._model.pointStyle = icon;

            })
        },
    }]
});

And the following code will add dynamic images.

new Chart(chartCanvas, {
    type: 'bubble',
    data: chartData,
    options: chartOptions,
    plugins: [{
        afterUpdate: function (chart, options) {
            chart.getDatasetMeta(0).data.forEach((d, i) => {

                var icon = new Image();
                icon.src = jsonUserData[i].avatar;
                icon.width = 22;
                icon.height = 22;

                d._model.pointStyle = icon;

            })
        },
    }]
});

Result on my side:

enter image description here

Leave a comment