JSFiddle - React, Tailwind, and code Playground

by Nabaraj Saha

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

JavaScript

var ctx = document.getElementById("myChart");

// The original draw function for the line chart. This will be applied after we have drawn our highlight range (as a rectangle behind the line chart).
var originalLineDraw = Chart.controllers.line.prototype.draw;
// Extend the line chart, in order to override the draw function.
Chart.helpers.extend(Chart.controllers.line.prototype, {
  draw: function() {
    var chart = this.chart;
    // Get the object that determines the region to highlight.
    var yHighlightRange = chart.config.data.yHighlightRange;

    // If the object exists.
    if (yHighlightRange !== undefined) {
      if (yHighlightRange.begin.length == yHighlightRange.end.length) {
        for (yCount = 0; yCount < yHighlightRange.begin.length; yCount++) {
          var ctx = chart.chart.ctx;

          var yRangeBegin = yHighlightRange.begin[yCount];
          var yRangeEnd = yHighlightRange.end[yCount];
          var yRangeColor = yHighlightRange.color[yCount];

          var xaxis = chart.scales['x-axis-0'];
          var yaxis = chart.scales['y-axis-0'];

          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 = yRangeColor;
          // 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();
        }
      } else {
        console.warn("yHighlightRange.begin and yHighlightRange.end are not the same length")
     ...