Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js get the nearest point when clicked on canvas

is there a way to get the nearest point when clicked anywhere on canvas? Maybe somehow harvest the core 'nearest' method? Thanks

like image 659
Ondra da Skacel Avatar asked May 31 '19 03:05

Ondra da Skacel


1 Answers

I think you will find getElementsAtXAxis very helpful.

Basically, getElementsAtXAxis has a very similar behaviour to getElementsAtEvent although when the click event doesn't intersect a point of the chart, it will return the nearest ChartElement.

The only downside is that it will return all the ChartElement on the nearest x-axis index.

So, if you use multiple datasets, this might not be the best choice for you.

Code example:

canvas.onclick = function(e) {
    const elts = chart.getElementsAtXAxis(simulatedEvent);
    if (elts && elts.length) {
        // Do something with elts[0]
    }
};

If anyone is looking for the related piece of code, it's in core.controller.js:

getElementAtEvent: function(e) {
    return Interaction.modes.nearest(this, e, {intersect: true});
},

getElementsAtEvent: function(e) {
    return Interaction.modes.index(this, e, {intersect: true});
},

getElementsAtXAxis: function(e) {
    return Interaction.modes.index(this, e, {intersect: false});
},
like image 52
La masse Avatar answered Sep 24 '22 00:09

La masse