ChartJS 3获取堆叠垂直条形高度 实现小条形标签外置
问题解答
1. getProps()返回height为undefined的原因
ChartJS 3.x+的getProps()方法必须显式传入需要读取的属性名列表作为参数,才会返回对应属性的有效值,否则默认返回的对象中未声明的属性都是undefined。你在控制台能看到height字段是因为控制台打印时会拉取元素的完整原型属性,实际运行时直接访问无值。
正确读取height的写法是:
// 传入要获取的属性数组 const { height } = context.chart.getDatasetMeta(context.datasetIndex).data[context.dataIndex].getProps(['height']);
2. 堆叠条总高度判断+标签位置调整实现方案
要获取整个堆叠条的总高度,不需要逐个累加分段高度,直接通过y轴刻度的像素转换方法计算即可:
- 先统计当前dataIndex对应所有dataset的数值总和
- 用y轴的
getPixelForValue方法将0值和总和值转换为画布像素,差值就是堆叠条的总高度 - 总高度低于阈值时,将datalabels的anchor设为
end,对齐到堆叠条顶部即可
修正后完整代码
var ctx = document.getElementById("myChart"); Chart.register(ChartDataLabels); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: 'red' }, { label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: 'blue' }] }, options: { scales: { x: { stacked: true }, y: { stacked: true } }, plugins: { datalabels: { anchor: context => { const dataIndex = context.dataIndex; const yScale = context.chart.scales.y; // 计算当前堆叠条的总数值 let totalValue = 0; context.chart.data.datasets.forEach(ds => { totalValue += ds.data[dataIndex]; }); // 计算堆叠条总高度(单位:像素) const totalHeight = yScale.getPixelForValue(0) - yScale.getPixelForValue(totalValue); const threshold = 30; // 可自定义高度阈值 // 总高度低于阈值时标签显示在顶部 return totalHeight < threshold ? 'end' : 'center'; }, align: context => { // 配合anchor调整对齐方式,外部显示时标签在条形上方 const dataIndex = context.dataIndex; const yScale = context.chart.scales.y; let totalValue = 0; context.chart.data.datasets.forEach(ds => { totalValue += ds.data[dataIndex]; }); const totalHeight = yScale.getPixelForValue(0) - yScale.getPixelForValue(totalValue); const threshold = 30; return totalHeight < threshold ? 'end' : 'center'; } } } } });
内容的提问来源于stack exchange,提问作者meexo
相关产品推荐
相关产品推荐

