如何在Chart.js最新版堆叠柱状图中实现反向圆角?
实现Chart.js柱状图的反向圆角效果

我正在使用最新版Chart.js,如何在柱状图中实现图中的反向圆角效果?
当前数据配置:
const myData = { labels: ["1 Jan", "2 Jan", "3 Jan", "4 Jan", "5 Jan", "6 Jan", "7 Jan", "8 Jan"], datasets: [{ label: 'Employee', backgroundColor: background_1, data: [12, 59, 5, 56, 58, 12, 59, 87, 45], borderRadius: 100, barPercentage: 0.5, // Adjust this value to change the width of the bars categoryPercentage: 0.3, borderColor: 'white', borderWidth: 1 }, { label: 'Engineer', backgroundColor: background_2, data: [12, 59, 5, 56, 58, 12, 59, 85, 23], borderRadius: 100, barPercentage: 0.5, // Adjust this value to change the width of the bars categoryPercentage: 0.3, borderColor: 'white', borderWidth: 1, borderSkipped: 'middle' }] }
解决方案
Chart.js 的 borderRadius 支持对象形式的配置,可精准控制柱子四个角的圆角半径,以此实现反向圆角效果。只需针对两个数据集分别设置不同方向的圆角:
- 给「Employee」数据集设置底部圆角、顶部直角
- 给「Engineer」数据集设置顶部圆角、底部直角
修改后的配置代码:
const myData = { labels: ["1 Jan", "2 Jan", "3 Jan", "4 Jan", "5 Jan", "6 Jan", "7 Jan", "8 Jan"], datasets: [{ label: 'Employee', backgroundColor: background_1, data: [12, 59, 5, 56, 58, 12, 59, 87, 45], // 仅底部两个角设置圆角 borderRadius: { topLeft: 0, topRight: 0, bottomLeft: 100, bottomRight: 100 }, barPercentage: 0.5, categoryPercentage: 0.3, borderColor: 'white', borderWidth: 1 }, { label: 'Engineer', backgroundColor: background_2, data: [12, 59, 5, 56, 58, 12, 59, 85, 23], // 仅顶部两个角设置圆角 borderRadius: { topLeft: 100, topRight: 100, bottomLeft: 0, bottomRight: 0 }, barPercentage: 0.5, categoryPercentage: 0.3, borderColor: 'white', borderWidth: 1 }] }
如果需要针对单个数据点做差异化圆角,还可以将 borderRadius 设置为数组形式,但针对整个数据集的对象配置已能满足图中需求。
内容的提问来源于stack exchange,提问作者budz
相关产品推荐
相关产品推荐

