When I copy the image of the chart rendered, I get the background as black. Is there a way to change it to white or any other color I want?
Asked
Active
Viewed 11 times
1 Answers
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],
})
};

FC5570
- 163
- 4
- 12