我有一个暗模式切换按钮,我希望 Chart.js 响应亮/暗模式。所以我设置了两组默认选项:
const defaults = {
scale: {
border: {
color: dark ? '#FFFFFF19' : '#00000019',
},
grid: {
color: dark ? '#FFFFFF19' : '#00000019',
},
},
}
每当主题模式更改时,
Chart.defaults
都会更新,并为每个图表调用chart.update()
。但新的默认选项仍未应用。创建图表后如何应用更新的默认选项?
这是我的设置代码:
import {
CategoryScale,
Chart,
LineController,
LineElement,
LinearScale,
PointElement,
TimeScale,
Title,
Tooltip,
} from 'chart.js';
import {merge, remove} from 'lodash';
import type {ChartConfiguration, ChartConfigurationCustomTypesPerDataset, ChartItem, ChartType, DefaultDataPoint} from 'chart.js';
Chart.register(Title, Tooltip, CategoryScale, TimeScale, LinearScale, LineController, PointElement, LineElement);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const charts: Array<RmsChart<any, any, any>> = [];
export class RmsChart<
TType extends ChartType = ChartType,
TData = DefaultDataPoint<TType>,
TLabel = unknown,
> extends Chart<TType, TData, TLabel> {
constructor(item: ChartItem, config: ChartConfiguration<TType, TData, TLabel> | ChartConfigurationCustomTypesPerDataset<TType, TData, TLabel>) {
super(item, config);
charts.push(this);
}
destroy() {
super.destroy();
remove(charts, this);
}
}
function cssVarColor(variable: string, alpha = 1.0) {
const cssVar = getComputedStyle(document.documentElement).getPropertyValue(variable);
if (!cssVar)
console.warn(`Cannot get css variable ${variable}`);
const color = cssVar || '0,0,0';
return `rgba(${color}, ${alpha})`;
}
async function syncThemeColor() {
await nextTick();
const defaults = {
elements: {
line: {
backgroundColor: cssVarColor('--v-theme-chart-primary', 0.12),
borderColor: cssVarColor('--v-theme-chart-primary', 0.6),
},
point: {
backgroundColor: cssVarColor('--v-theme-chart-point'),
borderColor: cssVarColor('--v-theme-chart-primary'),
},
},
scale: {
border: {
color: cssVarColor('--v-theme-chart-grid', 0.1),
},
grid: {
color: cssVarColor('--v-theme-chart-grid', 0.1),
},
},
};
merge(Chart.defaults, defaults);
console.log(charts[0].options);
for (const chart of charts)
chart.update();
console.log('syncThemeColor', Chart.defaults);
}
watch(useIsDarkMode(), syncThemeColor, {immediate: true});
我还尝试了
chart.update()
不同的更新模式,例如“重置”、“无”、“默认”和“活动”。不应用新的默认选项。
我自己找到了答案。由于每当图表更新时都会重新计算可编写脚本的选项,因此我只需将值包装在函数中即可。更换主题时记得拨打
chart.update()
。
const defaults = {
// ...
scale: {
border: {
// color: cssVarColor('--v-theme-chart-grid', 0.1),
color: () => cssVarColor('--v-theme-chart-grid', 0.1),
},
},
};