How can I refresh the background color of dataset. I would like to change the colors when I switch to dark mode. I thought I can do it with update(), but it seems I can't.
When you switch to dark mode, the backgroud color is changing in the example, but you need to regresh the page (run the code again) to switch the colors of the chart too.
Below is my current implementation.
Any help would be appreciated.
const labels = [
'January',
'February',
'March',
'April',
'May',
'June',
];
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
data: [29, 45, 26],
backgroundColor: [
getComputedStyle(document.documentElement).getPropertyValue('--color1').trim(),
getComputedStyle(document.documentElement).getPropertyValue('--color2').trim(),
getComputedStyle(document.documentElement).getPropertyValue('--color3').trim()
]
}]
};
const config = {
type: 'bar',
data: data
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
myChart.update();
alert('switched');
});
:root {
--color1: red;
--color2: green;
--color3: blue;
}
@media (prefers-color-scheme: dark) {
body {
background-color: #222;
}
:root {
--color1: yellow;
--color2: purple;
--color3: pink;
}
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div>
<canvas id="myChart"></canvas>
</div>
This is because you dont actually update anything, you will also need to update the colors before calling the update function:
const labels = [
'January',
'February',
'March',
'April',
'May',
'June',
];
const getBackgroundColors = () => ([
getComputedStyle(document.documentElement).getPropertyValue('--color1').trim(),
getComputedStyle(document.documentElement).getPropertyValue('--color2').trim(),
getComputedStyle(document.documentElement).getPropertyValue('--color3').trim()
])
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
data: [29, 45, 26],
backgroundColor: getBackgroundColors()
}]
};
const config = {
type: 'bar',
data: data
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
myChart.data.datasets[0].backgroundColor = getBackgroundColors();
myChart.update();
alert('switched');
});
:root {
--color1: red;
--color2: green;
--color3: blue;
}
@media (prefers-color-scheme: dark) {
body {
background-color: #222;
}
:root {
--color1: yellow;
--color2: purple;
--color3: pink;
}
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div>
<canvas id="myChart"></canvas>
</div>