'How to change chart background colour when exporting to PDF with chart.js

I am new to chart.js and trying to add a button that exports my chart to a PDF file.

The chart exports with a black background however, I want to change the background to white.

I have tried adding the below code to change the background but am not sure where I'm going wrong.

How would I change the chart background so it's white when I export to PDF?

    const bgColor = {
    id: 'bgColor',
    beforeDraw: (chart, steps, options) => {
        const {ctx, width, height} = chart;
  ctx.fillStyle = options.backgroundColor;
  ctx.fillRect(0, 0, width, height)
  ctx.restore();
    }
}

var options = {
    responsive: true,
    maintainAspectRatio: true,
    scale: {
        min: 0,
  max: 10,
        stepSize: 1
    },
    scales: {
        r: {
            pointLabels: {
                font: {
                    size: 15
                        
                    }
                }
            }
        },
    plugins: {
        bgColor: {
            backgroundColor: 'white'
        },
        legend: {
            labels: {
                boxWidth: 0,
                font: {
                    size: 30
                }
            } 
        }
    }
}

const radarChart = new Chart(document.getElementById('radarChart'), {
    type: 'radar',
data: data,     
    options: options
})

Chart pdf



Solution 1:[1]

This is because you never register your plugin so it does not do anything. You can register it locally to a single chart like this:

const bgColor = {}; // Plugin Code

const chart = new Chart('canvasId', {
    data: data,
    options: options,
    plugins: [bgColor]
});

Or you can register it locally so it applies to all charts like so:

const bgColor = {}; // Plugin Code
Chart.register(bgColor); // V3 syntax
Chart.plugins.register(bgColor) // V2 syntax

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LeeLenalee