0👍
So I found the solution by myself. In the ‘animation’ variable passed to the onComplete callback is an array ‘animation.chart.active’ which can be looped to find the active dataset Indexes. The active array is only populated when hovering over the bars of the graph, thats why the sum of points are only displayed when hovering over the bars.
The whole code looks now like this:
function success_(data) {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: data,
options: {
title: {
display: true,
text: 'Square Meters done per day'
},
tooltips: {
mode: 'index',
intersect: false
},
maintainAspectRatio: false,
responsive: true,
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
},
animation: {
onComplete: function(animation) {
//alert('onAnimationComplete');
if (typeof animation.chart !== 'undefined' && typeof animation.chart.active !== 'undefined') {
var active_datasets = new Array();
//loop through active dataset to get the dataset indexes
//which are visible to the user
animation.chart.active.forEach(function(active_ds) {
active_datasets.push(active_ds._datasetIndex);
})
//loop through datasets to get the points for active datasets
var sqm = 0;
var i = 0;
this.data.datasets.forEach(function (dataset) {
if (active_datasets.indexOf(i) != -1) {
dataset.data.forEach(function (points) {
sqm = sqm + points;
})
}
i = i + 1;
})
$("#SquareMeterSurface").val(parseFloat(sqm).toFixed(1) + ' m2');
}
}
},
}
});
};
and the ajax call to invoce a .Net Core MVC action is like this:
$.ajax({
url: '/YourController/YourActionForGraph/',
type: 'GET',
data: {
'param1': $('#param1').val(),
'param2': $('#param2').val()
},
dataType: 'json',
success: success_,
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}
});
- Chartjs-Async showing data in pieChart from chart.js with typescript
- Chartjs-Not being able to display value from json data into chart js
0👍
Thanks for your hint. This one helped me, so I came up with the following solution:
`const options = {
radius: "100%",
cutout: "90%",
animation: {
onComplete: function (animation) {
console.log(animation.chart.getDatasetMeta(0));
},
},
};`
You can call getDatasetMeta(index)
on the chart object
and you will get an object with all current data used to construct the chart. Here you find the total property with the current sum.
See: https://www.chartjs.org/docs/latest/developers/api.html#getdatasetmeta-index