You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Chart.js环形图中的单个扇区比其他扇区更厚?

实现Chart.js环形图单个扇区加厚的方案

可以实现,核心思路是叠加多个数据集——因为Chart.js的单个环形数据集无法为不同扇区设置差异化厚度,我们通过添加第二个数据集单独承载需要加厚的扇区,调整其半径参数来实现厚度差异。

以下是基于你提供的代码修改后的实现,让蓝色扇区比红色扇区厚25%:

const config: ChartConfiguration = {
  type: 'doughnut',
  data: {
    labels: ['Red', 'Blue'],
    datasets: [
      // 基础数据集:承载所有扇区,蓝色设为透明(仅显示红色)
      {
        hoverOffset: 24,
        backgroundColor: ['rgb(255, 9, 132)', 'transparent'],
        borderWidth: 0,
        label: '# of Points',
        data: [75, 25],
        // 基础环形的半径设置
        radius: '100%',
        cutout: '70%'
      },
      // 加厚数据集:仅承载蓝色扇区,调整半径实现加厚25%
      {
        hoverOffset: 24,
        backgroundColor: ['rgb(54, 162, 235)'],
        borderWidth: 0,
        label: '# of Points (Thick)',
        data: [25],
        // 外半径比基础数据集大25%,内半径保持一致,厚度自然增加25%
        radius: '125%',
        cutout: '70%',
        offset: 0
      }
    ],
  },
  options: {
    plugins: {
      legend: {
        display: false,
      },
      tooltip: {
        mode: 'index',
        intersect: false,
        position: 'nearest',
        // 合并tooltip提示,避免重复显示
        callbacks: {
          label: function(context) {
            const value = context.parsed;
            return `# of Points: ${value}%`;
          }
        }
      },
    },
    scales: {}
  },
};
new Chart(ctx, config);

关键说明:

  • 基础数据集:仅显示红色扇区,蓝色设为transparent,同时定义环形的基础尺寸(radius: '100%',cutout: '70%')。
  • 加厚数据集:仅包含蓝色扇区的数据,将radius设置为125%(比基础数据集大25%),cutout保持和基础数据集一致,这样蓝色扇区的厚度(外半径-内半径)就比红色扇区厚25%。
  • 配置tooltip回调函数,保证交互体验统一,避免重复提示。

内容的提问来源于stack exchange,提问作者Ole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 04:52:52