I\'m working on building a simple line chart using Chart.js (the 2.0.2 beta) and I\'d like to highlight a particular range of the chart\'s background to highlight an \"accep
I ended up placing @xnakos code inside componentDidUpdate() callback. The advantage is that you should not set the opacity of the highlighted area to visible the graph like ctx.fillStyle = 'rgba(0, 255, 0, 0.3)' and no need to overwrite the fill method in @xnakos answer.
componentDidUpdate() {
Chart.pluginService.register({
beforeDraw: (chartInstance) => {
var chart = chartInstance;
// Get the object that determines the region to highlight.
var yHighlightRange = chart.config.data.yHighlightRange;
// If the object exists.
if (yHighlightRange !== undefined) {
var ctx = chart.chart.ctx;
var yRangeBegin = yHighlightRange.begin;
var yRangeEnd = yHighlightRange.end;
var xaxis = chart.scales["x-axis"];
var yaxis = chart.scales["y-axis"];
var yRangeBeginPixel = yaxis.getPixelForValue(yRangeBegin);
var yRangeEndPixel = yaxis.getPixelForValue(yRangeEnd);
ctx.save();
// The fill style of the rectangle we are about to fill.
ctx.fillStyle = yHighlightRange.fillStyle;
// Fill the rectangle that represents the highlight region. The parameters are the closest-to-starting-point pixel's x-coordinate,
// the closest-to-starting-point pixel's y-coordinate, the width of the rectangle in pixels, and the height of the rectangle in pixels, respectively.
ctx.fillRect(
xaxis.left,
Math.min(yRangeBeginPixel, yRangeEndPixel),
xaxis.right - xaxis.left,
Math.max(yRangeBeginPixel, yRangeEndPixel) -
Math.min(yRangeBeginPixel, yRangeEndPixel)
);
ctx.restore();
}
},
});
}
and the data object is as follow,
data = {
labels: [],
datasets: [...],
yHighlightRange: {
begin: 50,
end: 100,
fillStyle: "#7DD8D2",
},
};