JSFiddle - React, Tailwind, and code Playground

by avocado1

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<body>
  <canvas id="my-canvas"></canvas>
</body>

JavaScript

const backgroundPlugin = {
  beforeDatasetDraw(chart, easing) {

    const ctx = chart.chart.ctx;
    const chartArea = chart.chartArea;

    ctx.save();

    const colors = [
      'red',
      'green',
      'yellow',
      'blue'
    ];
    const randomNumber = Math.floor(Math.random() * colors.length);

    ctx.fillStyle = colors[randomNumber];

    console.log('refreshing background');
    chart.getDatasetMeta(0).data.forEach((data, index, all) => {
      // Check if value > threshold (here 350)
      if (
        chart.config.data.datasets[0].data[index].y > 350
      ) {
        const nextPointX =
          index === all.length - 1 ?
          chartArea.left :
          all[index + 1]._model.x;

        // Create vertical rectangle of color between current point and next point
        ctx.fillRect(
          nextPointX,
          chartArea.top,
          Math.abs(all[index]._model.x - nextPointX),
          chartArea.bottom - chartArea.top
        );
      }
    });
    ctx.restore();
  }
};

const chartDescription = {
  type: 'line',
  data: {
    datasets: [{
      fill: false,
      backgroundColor: 'black',
      borderColor: 'black',
      label: 'Risk',
      data: [{
          x: 1472410961,
          y: 200
        }, {
          x: 1472324561,
          y: 500
        }, {
          x: 1472268161,
          y: 200
        }, {
          x: 1472238161,
          y: 783
        },
        {
          x: 1472233161,
          y: 300
        }
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        ticks: {
          callback(value) {
            var time = new Date(value * 1000);
            return (time.getMonth() + 1) + '/' + time.getDate() + ' ' + time.getHours();
          }
        }
      }]
    }
  },
  plugins: [backgroundPlugin]
};


const ctx = document.getElementById("my-canvas").getContext('2d');
const chart = new Chart(ctx, chartDescription);