Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Color the chartArea for each x point.
import { Easing, PluginServiceGlobalRegistration, PluginServiceRegistrationOptions } from 'chart.js';
export class BackgroundPlugin implements PluginServiceGlobalRegistration, PluginServiceRegistrationOptions {
id = 'background-plugin';
beforeDraw(chartInstance: Chart, easing: Easing, options?: any): void {
const chartOptions = chartInstance.options as any;
if (!('backgroundPlugin' in chartOptions) || !('backgroundColors' in chartOptions.backgroundPlugin)) {
return;
}
const backgroundColors = chartOptions.backgroundPlugin.backgroundColors;
const context = chartInstance.ctx;
const area = chartInstance.chartArea;
const meta = chartInstance.getDatasetMeta(0);
context.save();
for (let i = 0; i < backgroundColors.length - 1; i++) {
const start = meta.data[i]._model.x;
const stop = meta.data[i+1]._model.x;
context.fillStyle = backgroundColors[i];
context.fillRect(start, area.top, stop - start, area.bottom - area.top);
}
context.restore();
}
}
/*
Chart.pluginService.register(new BackgroundPlugin());
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.