0

I am using react Chartjs's scatter chart to plot a line chart for a set of X,Y points. I am trying to get the X and Y points when user right clicks anywhere on the chart by passing following function to onClick.

options={
         ...

        onClick: function(event) {
          let activeElement = Ref.current.chartInstance.getElementAtEvent(
            event
          );

          let res =
            Ref.current.chartInstance.data.datasets[
              activeElement[0]._datasetIndex
            ].data[activeElement[0]._index];
          
        }

         }

But this only works when I click on plotted line on the existing point and not when I click anywhere in the chart. If I click anywhere else other the line, returned activeElement will be empty list.

How can I get X and Y regardless of where I click in chart area?

srinivast6
  • 309
  • 3
  • 8

1 Answers1

1
  onClick: (e) => {

    const canvasPosition = Chart.helpers.getRelativePosition(e, chart);

    // replace .x. and .y. with the id of your axes below

    const dataX = chart.scales.x.getValueForPixel(canvasPosition.x);
    const dataY = chart.scales.y.getValueForPixel(canvasPosition.y);
},
chad steele
  • 828
  • 9
  • 13