1

I have a multiline chart drawn using chart.js. I want to get borderColor of the clicked point(datapoint) only, when the user clicks on a particular point.

For understanding, I have two lines in my multi-line chart called Prime and Fibonacci and My Second dataset drawn using dataset [12, 13, 15, 17, 111, 113, 117, 9, 3, 0] and [2, 3, 5, 7, 11, 13, 17, 13, 21, 34] respectively, both lines have a different borderColor green and red respectively.

Now, I want to catch only clicked point's borderColor when the user clicks on the datapoints. For example, when the user clicks on datapoint 111 which is from line Prime and Fibonacci then I should get borderColor as green, similarly when the user clicks on datapoint 11 from My Second dataset line, then I should get border color as red.

I have tried using below but it gives me both colors doesn't matter on which lines data point the user clicked.

var activePoints = lineChart.getElementsAtEvent(evt);
// Below code always gives me green and red, doesn't matter which line's data point the user clicked
activePoints[0]._chart.config.data.datasets[0].borderColor // Always gives green 
activePoints[0]._chart.config.data.datasets[1].borderColor // Always gives red

How can I do that? For quick setup take help of jsbin.

Thanks in Advance!

4

1 回答 1

2

经过长期的斗争和研究,我想出了以下解决方案。

它将_datasetIndex帮助我理解从Prime and FibonacciMy Second dataset行触发的点击事件。如果activePoints[0]._datasetIndex是,0那么它来自Prime and Fibonacci,类似地,如果activePoints[0]._datasetIndex是,1那么它来自My Second dataset

ctx.onclick = function(evt) {
    var activePoints = lineChart.getElementsAtEvent(evt);

    if (activePoints.length) {
      var mouse_position = Chart.helpers.getRelativePosition(evt, lineChart.chart);

      activePoints = $.grep(activePoints, function(activePoint, index) {
        var leftX = activePoint._model.x - 5,
            rightX = activePoint._model.x + 5,
            topY = activePoint._model.y + 5,
            bottomY = activePoint._model.y - 5;

        return mouse_position.x >= leftX && mouse_position.x <=rightX && mouse_position.y >= bottomY && mouse_position.y <= topY;
      });
      console.log(activePoints[0]._datasetIndex);
    }    
};

也就是说,这里是工作示例jsbin。我相信这将帮助许多遇到相同情况/问题的人。

于 2017-03-03T11:12:32.493 回答