[Chartjs]-How to fill the area between two vertical lines in the chart using chartjs library?

3๐Ÿ‘

โœ…

I think you need a dedicated plugin to do it.

I have created one (it could be improve), see snippet.

const plugin = {
  id: 'myfill',
  beforeDatasetsDraw(chart, args, options) {
    const {ctx, data} = chart;
    ctx.save();
    ctx.fillStyle  = 'rgba(47, 98, 156, 0.2)';
    ctx.beginPath();
    let meta = chart.getDatasetMeta(0);
    let e = meta.data[0];
    ctx.moveTo(e.x, e.y);
    e = meta.data[1];
    ctx.lineTo(e.x, e.y);
    meta = chart.getDatasetMeta(1);
    e = meta.data[1];
    ctx.lineTo(e.x, e.y);
    e = meta.data[0];
    ctx.lineTo(e.x, e.y);
    ctx.fill();
    ctx.restore();
  }
};
const ctx = document.getElementById('myChart');
const myChart = new Chart(ctx, {
   type: 'scatter',
   plugins: [plugin],
   data: {
     datasets: [{
            label: 'linha 1',            
            data:[
              {x: -11, y: 7},
              {x: -1, y: 8},
            ],
            showLine: true,
            borderColor: 'rgb(47, 98, 156)',
          }, 
          {
            label: 'linha 2',
            data: [
              {x: 0, y: 7},
              {x: 8, y: 8},
            ],
            showLine: true,
            borderColor: 'rgb(47, 98, 156)',
          }
        ]
        },
        options: {
          responsive: false,
        }
    });
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

Leave a comment