最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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/

发布评论

评论列表(0)

  1. 暂无评论