如何在Chart.js环形图中添加填充圆形并移除默认边距
解决方案:Chart.js环形图添加中心背景及移除边距
需求说明
- 给环形图(Doughnut Chart)中心添加带颜色的填充圆形背景
- 移除Chart.js自动添加的内边距和外边距
- 保留已实现的中心文本
目标效果:
当前效果:
修改后的完整代码
data = { labels: ['performance'], datasets: [{ label: 'performance', data: [90, 10], backgroundColor: ['#27AE60', '#3333331A'] }] }; config = { type: 'doughnut', data, options: { cutout: 200, legend: { display: false }, responsive: true, rotation: 210, // 起始角度(度) circumference: 300, radius: "50%", // 移除Chart.js内部边距 layout: { padding: 0 }, // 取消宽高比例锁定,让图表完全适配容器尺寸 maintainAspectRatio: false }, plugins: [{ id: 'center-content', beforeDraw: function (chart) { const width = chart.width; const height = chart.height; const ctx = chart.ctx; ctx.restore(); // 1. 绘制中心背景圆 const centerX = width / 2; const centerY = height / 2; // 根据环形内径计算背景圆半径 const bgRadius = 200 / 2; ctx.fillStyle = '#FFFFFF'; // 可根据需求修改背景色 ctx.beginPath(); ctx.arc(centerX, centerY, bgRadius, 0, 2 * Math.PI); ctx.fill(); // 2. 绘制中心文本 const fontSize = (height / 200).toFixed(2); ctx.font = `${fontSize}em sans-serif`; ctx.textBaseline = "middle"; ctx.fillStyle = '#333333'; // 文本颜色 const text = '90%'; const textX = Math.round((width - ctx.measureText(text).width) / 2); const textY = height / 2; ctx.fillText(text, textX, textY); ctx.save(); } }] }; new Chart('performance', config);
关键修改点说明
1. 添加中心背景圆
在自定义插件的beforeDraw方法中调整绘制顺序:先画背景圆,再绘制文本,确保文本显示在背景上方:
- 用
arc()方法绘制与环形内径匹配的圆形 - 通过
fillStyle设置背景色,可根据需求自行修改
2. 移除内外边距
- 在
options.layout中设置padding: 0,清除Chart.js默认的内部内边距 - 开启
maintainAspectRatio: false,让图表完全适配容器尺寸,避免自动生成额外边距 - 额外提示:如果容器本身有边距,需给承载图表的
<canvas>或父容器添加CSS样式margin: 0; padding: 0;
3. 修复语法错误
修正了原代码中label: 'performance;,的单引号缺失问题,避免运行报错
内容的提问来源于stack exchange,提问作者Abhishek Goswami
相关产品推荐
相关产品推荐

