您可以如下使用chartjs-plugin-datalabels:
new Chart(document.getElementById("myChart"), {
type: "bar",
data: {
labels: ['A', 'B', 'C'],
datasets: [{
label: "X",
data: [15, 8, 12],
backgroundColor: "red"
},
{
label: "Y",
data: [7, 6, 15],
backgroundColor: "blue"
},
{
label: "Z",
data: [6, 12, 10],
backgroundColor: "green"
}
]
},
options: {
plugins: {
datalabels: {
formatter: (value, context) => {
let total = context.chart.data.datasets[context.dataIndex].data.reduce((a, b) => a + b, 0);
return Math.round(1000 / total * value) / 10 + '%';
},
color: 'white'
}
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
canvas {
max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<canvas id="myChart" width="10" height="5"></canvas>