'Chart.js with x, y coordinates, getElementsAtEventForMode returns elements for index, not for event x coordinate

The data I work with, comes in formats like this:

 {
        label: 'red',
        data: [
          { x: 1, y: 2 },
          { x: 1.5, y: 1 },
          { x: 2, y: 2 },
          { x: 2.5, y: 2 },
        ],
      },
      {
        label: 'blue',
        data: [
          { x: 1, y: 4 },
          { x: 2, y: 3 },
          { x: 3, y: 4 },
          { x: 4, y: 3 },
        ],
}

X-axis is linear, and the x-values step size is undetermined. Chart.js can detect the correct labels fine and draws the lines correctly. But when I try to use getElementsAtEventForMode to get signals at a certain x coordinate, like this:

const signalsAtPoint = chart.getElementsAtEventForMode(
                event as unknown as Event,
                'index',
                { intersect: false },
                false 
              );
signalsAtPoint.forEach((signal) => {
            console.log(
              chart.data.datasets[signal.datasetIndex].data[signal.index]
            );
          });

It finds the index of first signal and for each signal, returns the data at that index in the signals own coordinates. So if I click at blue[2], I expect to get only one signal as a response, because red signal doesn't exist anymore at x-value 3. But instead I get { x:2, y:2 } for red signal, because that is what exists at index location 2 in the red array. https://stackblitz.com/edit/chart-js-version-3-pjyozz

Is this intended behavior? It is most definitely not getting "elements at event". Is mismatching x-axis values a thing that should not be done, even though the chart can correctly draw those kind of charts?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source