您可以构建一个插件来使其正常工作。我目前在一个 vue 版本中工作,但我已经尽力为你调整它。
模板
template: `
<base-chart
class="chart"
[datasets]="datasets"
[labels]="labels"
[options]="options"
[chartType]="'line'"
[plugin]="dataLabelPlugin">
</base-chart>
`
js添加插件
private options = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
plugins: [{
afterDatasetsDraw: this.dataLabelPlugin
}]
};
Js 定义了一个插件,在每个动画之后绘制数字。您可能需要根据上下文传入您正在修改的图表。
private dataLabelPlugin = function(chart, easing) {
// To only draw at the end of animation, check for easing === 1
const ctx = chart.ctx;
const fontSize = 12;
const fontStyle = 'normal';
const fontFamily = 'open sans';
const padding = 5;
chart.data.datasets.forEach((dataset, key) => {
let meta = chart.getDatasetMeta(key);
if (!meta.hidden) {
meta.data.forEach((element, index) => {
let position = element.tooltipPosition();
// Just naively convert to string for now
let dataString = dataset.data[index].toString();
ctx.fillStyle = '#676a6c';
ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
// Make sure alignment settings are correct
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
});
}
});
};
如果你得到这个工作,让我知道,我可以做出改变,使这个答案更正确。