[Chartjs]-Get X, Y onClick chart coordinates in ChartJS

6👍

For future readers, a workable solution:

chartClicked(event){
    var yTop = this.chart.chartArea.top;
    var yBottom = this.chart.chartArea.bottom;

    var yMin = this.chart.scales['y-axis-0'].min;
    var yMax = this.chart.scales['y-axis-0'].max;
    var newY = 0;

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

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

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

    console.log(newX, newY);
};

Credit to chart.js 2.0 current mouse coordinates tooltip

1👍

sorry for the old code i didn’t see the documentation may be you can find more userfull in the doc, i did on old school mode :).

Position based on client with height :

canvas.onclick = function(evt){
    alert(evt.pageX, evt.pageY)
};

Position based on Charts :

var config = {}; //different (data, datasets, tooltips ...)
var ctx = document.getElementById("canvas").getContext("2d");
var Charts= new Chart.Scatter(ctx, config);
canvas.onclick = function(evt){
  var activePoints = Charts.getElementsAtEvent(evt);
  var firstPoint = activePoints[0];
  if(firstPoint !== undefined){
    var label = Charts.data.labels[firstPoint._index];
    var value = Charts.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];

    alert(label + ": " + value.x);
    alert(label + ": " + value.y);
  }
};

Taken from there 🙂 Click events on Pie Charts in Chart.js thanks for him.
Regards.

0👍

getValueForPixel can be used to get the value of an axis associated with a particular pixel on the chart.

const chart = new Chart(document.querySelector('canvas'), {
    // other configuration...
    data: someData,
    options: {
        onClick(e) {
            // coordinates of click relative to canvas
            const { x, y } = Chart.helpers.getRelativePosition(e, chart);
            // can also use const x = e.native.offsetX, y = e.native.offsetY;
            
            // get values relative to chart axes
            const dataX = chart.scales.x.getValueForPixel(x);
            const dataY = chart.scales.y.getValueForPixel(y);
        }
    }
});

See Converting Events to Data Values in the Chart.js 4.3.1 documentation.

Leave a comment