[Chartjs]-Hover/click area in filled line chart in chart.js

0👍

You can calculate if the mouse is in the area by getting the value of the y axis, index of the x axis and then calculate the max fill and then check if the yVal is lower as that:

var chart_canvas = document.getElementById("myChart");
var stackedLine = new Chart(chart_canvas, {
  type: 'line',
  data: {
    labels: ["0.0", "0.2", "0.4", "0.6", "0.8", "1.0"],
    fill: true,
    datasets: [{
      label: 'Usage',
      pointRadius: 3,
      data: [.5, .3, .2, .1, .4, .3],
      borderWidth: 1,
      fill: true
    }, {
      label: 'Popularity',
      pointRadius: 3,
      data: [.0, .1, .2, .4, .1, .4],
      borderWidth: 1,
      fill: true
    }]
  },
  options: {
    scales: {
      y: {
        stacked: true,
      }
    },
    onHover: (evt, activeEls, chart) => {
      let yVal = chart.scales.y.getValueForPixel(evt.y);
      let index = chart.scales.x.getValueForPixel(evt.x);

      let maxFilledArea = chart.data.datasets.reduce((acc, curr) => (acc + curr.data[index]), 0)

      if (yVal <= maxFilledArea) {
        console.log('Mouse in filled area')
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>

<main>
  <canvas id="myChart" width="500" height="500"></canvas>
</main>

Leave a comment