刷新chart.js数据集背景颜色



如何刷新数据集的背景颜色?当我切换到暗模式时,我想改变颜色。我认为我可以用update()来做,但似乎我不能。

当您切换到暗模式时,背景颜色在示例中发生了变化,但是您需要刷新页面(再次运行代码)来切换图表的颜色。

下面是我当前的实现。

如有任何帮助,不胜感激。

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>

这是因为你实际上没有更新任何东西,你还需要在调用更新函数之前更新颜色:

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>

最新更新