javascript

Use image as chart datasets background Chart.js

We know that Chart.js uses colors as its background to plot charts. Do you know that we can also use an image as a background for these datasets?

const img = new Image();
img.src = 'https://placeimg.com/640/480/any';
img.onload = function() {
    const ctx = document.getElementById('chart').getContext('2d');
    const fillPattern = ctx.createPattern(img, 'repeat');

    const chart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Item 1', 'Item 2', 'Item 3'],
            datasets: [{
                data: [90, 80, 90],
                backgroundColor: fillPattern
            }]
        }
    });
};

We are using an image as the background for columns of bar chart created using Chart.js library. We are assigning the image as the background for the chart using the backgroundColor property for the dataset. We are creating a pattern of the image using the createPattern() function and then passing it to the backgroundColor property.

A live demo for the above code is as below.

Was this helpful?