问题
I have developed a single Stacked bar with three section or data source. I want to know which section I have clicked.
This is my code .ts
file
this.chart = new Chart("Chart1", {
type: 'bar',
data: {
datasets: [{
label: 'Data1',
data: [27],
},
{
label: 'Data2',
data: [40],
},
{
label: 'Data3',
data: [12],
}
],
}
});
showData(evt:any){
var data = this.chart.getElementsAtEvent(evt)
console.log(data[0]._model); // it prints the value of the property
}
In the data
I am not getting data object
rather I getting chart
configuration but I just want to get the record which I clicked.
html
file
<div id="mydiv">
<canvas id="Chart1" (click)="showData($event)"></canvas>
</div>
This is my Bar
回答1:
You can define the showData
function as follow, this will also if your datasets contain more than one value:
function showData(evt) {
const datasetIndex = chart.getElementAtEvent(event)[0]._datasetIndex;
const index = chart.getElementAtEvent(event)[0]._index;
const model = chart.getElementsAtEvent(event)[datasetIndex]._model;
console.log(model.datasetLabel, chart.config.data.datasets[datasetIndex].data[index]);
}
Instead of adding the (click)
event handler directly on the canvas
, I would also rather define the onClick
function within the chart options as follows:
options: {
onClick: showData,
Please have a look at the runnable code snippet.
function showData(evt) {
const datasetIndex = chart.getElementAtEvent(event)[0]._datasetIndex;
const index = chart.getElementAtEvent(event)[0]._index;
const model = chart.getElementsAtEvent(event)[datasetIndex]._model;
console.log(model.datasetLabel, chart.config.data.datasets[datasetIndex].data[index]);
}
const chart = new Chart("Chart1", {
type: 'bar',
data: {
labels: ['A', 'B'],
datasets: [{
label: 'Data1',
data: [27, 22],
backgroundColor: 'red'
},
{
label: 'Data2',
data: [40, 15],
backgroundColor: 'orange'
},
{
label: 'Data3',
data: [12, 31],
backgroundColor: 'blue'
}
]
},
options: {
onClick: showData,
legend: {
display: false
},
tooltips: {
enabled: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true
}
}]
}
}
});
canvas {
max-width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="Chart1" height="200"></canvas>
来源:https://stackoverflow.com/questions/62425882/getting-clicked-object-from-each-section-of-a-single-stack-bar-as-my-stack-bar-h