0👍
This is because it only runs after the animation is done. To achieve what you want you need to use a custom plugin.
const ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
data: {
labels: ['21Q1', '21Q2', '21Q3', '21Q4', '22Q1', '22Q2', '22Q3', '22Q4', ],
datasets: [{
type: 'bar',
label: 'Y Value',
data: [2, 3, 4, 4, 5, 7, 5, 4, ],
borderWidth: 1,
backgroundColor: '#1E77E5',
}, ],
},
options: {
responsive: true,
animation: {},
},
plugins: [{
id: 'labels',
afterDraw: (chart, args, opts) => {
const ctx = chart.ctx;
ctx.textAlign = 'center';
ctx.fillStyle = "rgba(0, 0, 0, 1)";
ctx.textBaseline = 'bottom';
ctx.fillStyle = "#ffffff";
// Loop through each data in the datasets
chart.data.datasets.forEach(function(dataset, i) {
var meta = chart.getDatasetMeta(i);
if (meta.hidden == null) {
meta.data.forEach(function(bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar.x, bar.y - 5);
});
}
});
}
}]
});
canvas { background-color : black;
}
body {
background-color:Black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<body>
<canvas id="myChart" width="600" height="400"></canvas>
</body>
There is already a plugin with customization for this that you can use:
https://chartjs-plugin-datalabels.netlify.app/
- Chartjs-Implementing local storage in a dynamic chart – chart js
- Chartjs-Tiny error in the ChartJs book
Source:stackexchange.com