[Chartjs]-Getting the closest intersection to a click on Chart.js

1👍

You could use onClick option of chart in order to catch click event (instead of adding a listener to the canvas). In this way the passed event is already normalized.

The callback could be something like that, in order to have the closest tick:

options: {
  ...
  onClick(event, elements, chart) {
    const scale = chart.scales.r;
    const posY = Math.abs(scale.getDecimalForPixel(event.y) - 0.5);
    const posX = Math.abs(scale.getDecimalForPixel(event.x) - 0.5);
    const scalePosition = Math.max(posY, posX);
    const value = Math.round(scalePosition * 10);
    console.log(['none', 'low', 'mid-low', 'mid', 'mid-high', 'high'][value]); // shows value
  },
  ...

Leave a comment