7

Given a line chart in chart.js with areas under the curve filled. Is there a way to get a useful event when the user hovers over or clicks the filled area?

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',
            data: data[0],
        },
        {
            label: 'Popularity',
            data: data[1],
        }]
    },
    options: {
        onHover: function (elements) {
            console.log(elements);
        }
        // more stuff
    }
});

I tried onHover but when in the filled area, the only argument is an empty array.

I have a stacked, filled chart as in the image with curved lines. I would like an event when the mouse is anywhere in the light grey area.

example of filled line chart with chart.js (with stacking)

EDIT Here's a fiddle: https://jsfiddle.net/markv/rvqjkrp9/1/

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mark
  • 18,730
  • 7
  • 107
  • 130

1 Answers1

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>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69