0👍
✅
For Chart.js v3 and v4,
Replace instance.chart.update()
with instance.update()
should resolve the issue.
Aside, there are also some codes that need to be migrated for example Chart.defaults.global according to the documentation if you are working from Chart.js v1.
While I think from version 3 onwards, Chart.defaults.color
won’t able to update the font color for axes, axes’ label as well. Thus, you should update each instance for the axes (instance.config.options.scales[scale].grid.color
) and axes label (instance.config.options.scales[scale].ticks.color
) colors accordingly.
function changeTheme(darkTheme = false) {
if (darkTheme) {
document.body.classList.add('dark-theme');
Chart.defaults.color = 'white';
} else {
document.body.classList.remove('dark-theme');
Chart.defaults.color = 'black';
}
// Force updates to all charts
Chart.helpers.each(Chart.instances, function (instance) {
if (darkTheme) {
for (let scale in instance.config.options.scales) {
// Update axes grid color
instance.config.options.scales[scale].grid.color = 'white';
instance.config.options.scales[scale].grid.color = 'white';
instance.config.options.scales[scale].grid.borderColor = 'white';
instance.config.options.scales[scale].grid.borderColor = 'white';
// Update axes label font color
instance.config.options.scales[scale].ticks.color = 'white';
instance.config.options.scales[scale].ticks.color = 'white';
}
} else {
for (let scale in instance.config.options.scales) {
// Update axes grid color
instance.config.options.scales[scale].grid.color =
'rgba(0, 0, 0, 0.1)';
instance.config.options.scales[scale].grid.color =
'rgba(0, 0, 0, 0.1)';
instance.config.options.scales[scale].grid.borderColor =
'rgba(0, 0, 0, 0.1)';
instance.config.options.scales[scale].grid.borderColor =
'rgba(0, 0, 0, 0.1)';
// Update axes label font color
instance.config.options.scales[scale].ticks.color = 'black';
instance.config.options.scales[scale].ticks.color = 'black';
}
}
instance.update();
});
}
Reference: How to Implement Dark Mode in Chart JS (for Chart.JS version 3.6)
Source:stackexchange.com