javascript - Chart.js: Get point index from chart.getPointsAtEvent(e) - Stack Overflow

I am looking to make my chart (made with Chart.js) a little more interactive and I would like to get a

I am looking to make my chart (made with Chart.js) a little more interactive and I would like to get a point's index (of its dataset) with the following code:

canvas.onclick = function(e) {
  const points = chart.getPointsAtEvent(e);
  // something like `point.getIndex()` would be great so that I know where this point is in the original dataset
};

Anybody have a good solution for this?

I am looking to make my chart (made with Chart.js) a little more interactive and I would like to get a point's index (of its dataset) with the following code:

canvas.onclick = function(e) {
  const points = chart.getPointsAtEvent(e);
  // something like `point.getIndex()` would be great so that I know where this point is in the original dataset
};

Anybody have a good solution for this?

Share Improve this question asked Jul 6, 2015 at 18:54 MacksMacks 1,7767 gold badges23 silver badges39 bronze badges 1
  • I am currently solving this by looking up the index of the label but it is a bit hacky... – Macks Commented Jul 6, 2015 at 19:32
Add a ment  | 

1 Answer 1

Reset to default 2

You should be able to do an indexOf (instead of a label lookup) because it refers to the exact same object in the points collection

canvas.onclick = function (evt) {
    var points = chart.getPointsAtEvent(evt);
    alert(chart.datasets[0].points.indexOf(points[0]));
};

Also, for a multi series line chart getPointsAtEvent(evt) returns points from all datasets. So the same code would work irrespective of how many datasets you have or which of the datasets you click on.

Fiddle - http://jsfiddle/yxz2sjam/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745287412a4620647.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信