79229522

Date: 2024-11-27 09:02:16
Score: 0.5
Natty:
Report link

Based on the solution provided by @Mj_wales in vanila JS

Get X, Y onClick chart coordinates in ChartJS

here is the react approach

event.offsetY should be event.native.offsetY event.offsetX should be event.native.offsetX

          onHover: function (event) {

            var yTop = event.chart.chartArea.top;
            var yBottom = event.chart.chartArea.bottom;

            var yMin = event.chart.scales['y'].min;
            var yMax = event.chart.scales['y'].max;

            var newY = 0, newY1 = 0;

            if (event.native.offsetY <= yBottom && event.native.offsetY >= yTop) {
              newY = Math.abs((event.native.offsetY - yTop) / (yBottom - yTop));
              newY = (newY - 1) * -1;
              newY = newY * (Math.abs(yMax - yMin)) + yMin;
            };

            var xTop = event.chart.chartArea.left;
            var xBottom = event.chart.chartArea.right;
            var xMin = event.chart.scales['x'].min;
            var xMax = event.chart.scales['x'].max;
            var newX = 0;

            if (event.native.offsetX <= xBottom && event.native.offsetX >= xTop) {
              newX = Math.abs((event.native.offsetX - xTop) / (xBottom - xTop));
              newX = newX * (Math.abs(xMax - xMin)) + xMin;
            };
            console.log(newX, newY);
          },

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Mj_wales
  • Low reputation (1):
Posted by: kehinde salaudeen