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

Chart.js:点击环形图区块能否更新对应图例标签的字体样式?

实现点击环形图区块更新对应图例标签的字体大小和颜色

完全可以实现这个需求,核心是通过Chart.js的点击事件监听+自定义图例生成器来动态修改样式,以下是具体实现方案:

完整修改代码

// 记录当前选中的图例索引
let activeLegendIndex = null;

// 配置项
const config = {
  type: "doughnut",
  data: {
    labels: ["Green", "Red", "Blue"],
    datasets: [
      {
        data: [60, 80, 100],
        borderWidth: 0,
        backgroundColor: ["#009900", "#ff0000", "#3399ff"],
        hoverBackgroundColor: ["#009900", "#ff0000", "#3399ff"],
        cutout: "80%"
      }
    ]
  },
  options: {
    // 监听环形图区块点击事件
    onClick: (e, elements) => {
      if (elements.length > 0) {
        const index = elements[0].index;
        // 切换选中状态:重复点击同一区块则取消选中
        activeLegendIndex = activeLegendIndex === index ? null : index;
        // 更新图表触发图例重新渲染
        myChart.update();
      }
    },
    plugins: {
      legend: {
        position: "right",
        labels: {
          usePointStyle: true,
          pointStyle: "circle",
          // 自定义图例标签生成逻辑,动态设置样式
          generateLabels: (chart) => {
            const { labels, datasets } = chart.data;
            if (!labels.length || !datasets.length) return [];

            return labels.map((label, index) => {
              const isActive = index === activeLegendIndex;
              return {
                text: label,
                fillStyle: datasets[0].backgroundColor[index],
                font: {
                  size: isActive ? 18 : 11, // 选中时字体放大到18,默认11
                  weight: isActive ? "bold" : "normal"
                },
                color: isActive ? "#000" : "#666", // 选中时文字改为黑色,默认灰色
                pointStyle: "circle"
              };
            });
          }
        }
      }
    }
  }
};

// 初始化图表
const myChart = new Chart(document.getElementById("myChart"), config);

关键逻辑说明

  • activeLegendIndex:用来追踪当前选中的区块索引,初始为null表示无选中项
  • 图表onClick事件:捕获点击的环形图区块,更新选中状态后调用update()触发图表重新渲染
  • generateLabels:Chart.js提供的自定义图例生成接口,根据选中状态动态修改对应标签的字体大小、颜色和粗细

测试时点击任意环形图区块,对应的图例标签会立刻切换样式;再次点击同一区块则恢复默认样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:42:56