Chartjs-Image of chart has black background (Chart.js v4.3.0)

0👍

This can be done by using Canvas and the afterRender hook. Create your plugin with the afterRender hook which when called gets the canvas of the chart.js element, and changes its fillStyle.

The plugin:

const plugin = {
    id: 'after-render',
    
    afterRender: (c) => {
        const ctx = document.getElementById('containerId').getContext('2d');
        ctx.save();
        // The next line is essential to prevent unusual behavior.
        // As it causes the whole chart to go blank, when removed
        // Technique is taken from:
        // https://stackoverflow.com/a/50126796/165164
        ctx.globalCompositeOperation = 'destination-over';
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, c.width, c.height);
        ctx.restore();
    }
};

Change containerId to what you passed as the id in the html canvas tag.

And then, pass this plugin in the plugins option in the Chart constructor:

    new Chart(document.getElementById('consumptions'), {
        // ... options
        plugins: [plugin],
    })
};

Leave a comment