2👍
✅
Basically, you need to check whether a particular dataset is hidden or not, before drawing the text on animation complete.
To accomplish so, you can simply replace your onComplete
function with the following …
"onComplete": function() {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function(dataset, i) {
var isHidden = dataset._meta[0].hidden; //'hidden' property of dataset
if (!isHidden) { //if dataset is not hidden
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
}
});
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["2 Jan", "9 Jan", "16 Jan", "23 Jan", "30 Jan", "6 Feb", "13 Feb"],
datasets: [{
label: 'Data object 1',
data: [6, 87, 56, 15, 88, 60, 12],
fill: false,
backgroundColor: "#4082c4",
},
{
label: 'Data object 2',
data: [16, 57, 23, 60, 88, 40, 42],
fill: false,
backgroundColor: "#9082d4",
}
]
},
options: {
"hover": {
"animationDuration": 1
},
"animation": {
"duration": 1,
"onComplete": function() {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function(dataset, i) {
var isHidden = dataset._meta[0].hidden; //'hidden' property of dataset
if (!isHidden) { //if dataset is not hidden
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
}
});
}
},
legend: {
"display": true
},
tooltips: {
"enabled": true
},
scales: {
yAxes: [{
display: false,
gridLines: {
display: false
},
ticks: {
display: false,
beginAtZero: true
}
}],
xAxes: [{
gridLines: {
display: false
},
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>
Source:stackexchange.com