可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I've got a question regard Chart.js.
I've drawn multiple piecharts using the documentation provided. I was wondering if on click of a certain slice of one of the charts, I can make an ajax call depending on the value of that slice?
For example, if this is my data
var data = [ { value: 300, color:"#F7464A", highlight: "#FF5A5E", label: "Red" }, { value: 50, color: "#46BFBD", highlight: "#5AD3D1", label: "Green" }, { value: 100, color: "#FDB45C", highlight: "#FFC870", label: "Yellow" } ],
is it possible for me to click on the Red
labelled slice and call a url of the following form: example.com?label=red&value=300
? If yes, how do I go about this?
回答1:
Update: As @Soham Shetty comments, getSegmentsAtEvent(event)
only works for 1.x and for 2.x getElementsAtEvent
should be used.
.getElementsAtEvent(e)
Looks for the element under the event point, then returns all elements at the same data index. This is used internally for 'label' mode highlighting.
Calling getElementsAtEvent(event)
on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.
canvas.onclick = function(evt){ var activePoints = myLineChart.getElementsAtEvent(evt); // => activePoints is an array of points on the canvas that are at the same position as the click event. };
Example: https://jsfiddle.net/u1szh96g/208/
Original answer (valid for Chart.js 1.x version):
You can achieve this using getSegmentsAtEvent(event)
Calling getSegmentsAtEvent(event)
on your Chart instance passing an argument of an event, or jQuery event, will return the segment elements that are at that the same position of that event.
From: Prototype Methods
So you can do:
$("#myChart").click( function(evt){ var activePoints = myNewChart.getSegmentsAtEvent(evt); /* do something */ } );
Here is a full working example:
回答2:
Using Chart.JS version 2.1.3, answers older than this one aren't valid anymore. Using getSegmentsAtEvent(event) method will output on console this message:
getSegmentsAtEvent is not a function
So i think it must be removed. I didn't read any changelog to be honest. To resolve that, just use getElementsAtEvent(event)
method, as it can be found on the Docs.
Below it can be found the script to obtain effectively clicked slice label and value. Note that also retrieving label and value is slightly different.
var ctx = document.getElementById("chart-area").getContext("2d"); var chart = new Chart(ctx, config); document.getElementById("chart-area").onclick = function(evt) { var activePoints = chart.getElementsAtEvent(evt); if(activePoints.length > 0) { //get the internal index of slice in pie chart var clickedElementindex = activePoints[0]["_index"]; //get specific label by index var label = chart.data.labels[clickedElementindex]; //get value by index var value = chart.data.datasets[0].data[clickedElementindex]; /* other stuff that requires slice's label and value */ } }
Hope it helps.
回答3:
Chart.js 2.0 has made this even easier.
You can find it under common chart configuration in the documentation. Should work on more then pie graphs.
options:{ onClick: graphClickEvent } function graphClickEvent(event, array){ if(array[0]){ foo.bar; } }
It triggers on the entire chart, but if you click on a pie the model of that pie including index which can be used to get the value.
回答4:
If using a Donught Chart, and you want to prevent user to trigger your event on click inside the empty space around your chart circles, you can use the following alternative :
var myDoughnutChart = new Chart(ctx).Doughnut(data); document.getElementById("myChart").onclick = function(evt){ var activePoints = myDoughnutChart.getSegmentsAtEvent(evt); /* this is where we check if event has keys which means is not empty space */ if(Object.keys(activePoints).length > 0) { var label = activePoints[0]["label"]; var value = activePoints[0]["value"]; var url = "http://example.com/?label=" + label + "&value=" + value /* process your url ... */ } };
回答5:
Working fine chartJs sector onclick
ChartJS : pie Chart - Add options "onclick"
options: { legend: { display: false }, 'onClick' : function (evt, item) { console.log ('legend onClick', evt); console.log('legd item', item); } }
回答6:
If you are using TypeScript, the code is a little funky because there is no type inference, but this works to get the index of the data that has been supplied to the chart: // events public chartClicked(e:any):void { //console.log(e);
try { console.log('DS ' + e.active['0']._datasetIndex); console.log('ID ' + e.active['0']._index); console.log('Label: ' + this.doughnutChartLabels[e.active['0']._index]); console.log('Value: ' + this.doughnutChartData[e.active['0']._index]); } catch (error) { console.log("Error In LoadTopGraph", error); } try { console.log(e[0].active); } catch (error) { //console.log("Error In LoadTopGraph", error); } }
回答7:
To successfully track click events and on what graph element the user clicked, I did the following in my .js file I set up the following variables:
vm.chartOptions = { onClick: function(event, array) { let element = this.getElementAtEvent(event); if (element.length > 0) { var series= element[0]._model.datasetLabel; var label = element[0]._model.label; var value = this.data.datasets[element[0]._datasetIndex].data[element[0]._index]; } } }; vm.graphSeries = ["Series 1", "Serries 2"]; vm.chartLabels = ["07:00", "08:00", "09:00", "10:00"]; vm.chartData = [ [ 20, 30, 25, 15 ], [ 5, 10, 100, 20 ] ];
Then in my .html file I setup the graph as follows:
回答8:
I was facing the same issues since several days, Today i have found the solution. I have shown the complete file which is ready to execute.