Isaac King
Isaac King

Reputation: 368

Creating a diagonal shaded area in chart.js

I want to have a shaded diagonal area on a chart. Unfortunately, the fill attribute only fills the area that is vertically between two lines, and does not extend outwards to the edge of the chart, which results in this:enter image description here

As a workaround I can use a single line with a large borderWidth, which properly fills the entire area:enter image description here

However, borderWidth is specified in pixels, meaning that its width relative to the chart data will change depending on the display resolution.

How can I create a shaded area that covers the whole diagonal and whose width is specified in terms of the chart axes, not pixels?

Upvotes: 1

Views: 469

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31421

If you make sure your last points fall outside of the chartarea so the line contiues to keep going it will fill correclty:

const options = {
  type: 'line',
  data: {
    datasets: [{
      label: '# of Votes',
      data: [{
        x: 0,
        y: 20
      }, {
        x: 30,
        y: 0
      }],
    }, {
      label: '# of Points',
      fill: '-1',
      data: [{
        x: 0,
        y: 15
      }, {
        x: 25,
        y: 0
      }],
    }]
  },
  options: {
    scales: {
      x: {
        type: 'linear',
        min: 10,
        max: 20
      },
      y: {
        min: 0,
        max: 20
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>

Upvotes: 1

Related Questions