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

Chart.js多图表联动:悬停/点击同步更改同标签柱状图背景色

多Chart.js图表同步高亮同标签柱子解决方案

关键实现步骤

  • 保存所有图表实例:将每个Chart实例赋值给变量,方便后续跨图表操作
  • 统一重置颜色:每次点击时,先把所有图表的柱子恢复默认蓝色,避免颜色残留
  • 匹配同标签索引:遍历其他图表的标签数组,找出所有与点击标签一致的位置,修改对应柱子背景色
  • 刷新图表:修改颜色后调用update()方法更新图表显示

修改后的完整代码

<div style="width: 400px;">
  <canvas id="myChart1"></canvas>
  <canvas id="myChart2"></canvas>
</div>

<script>
  // 保存图表实例,方便后续操作
  let chart1, chart2;

  const ctx1 = document.getElementById('myChart1');
  chart1 = new Chart(ctx1, {
    type: 'bar',
    data: {
      labels: ['Mon', 'Thu', 'Wed', 'Thu', 'Fri', 'Sat'],
      datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: ["blue", "blue", "blue", "blue", "blue", "blue"], 
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      },
      onClick: function(evt, activeElements, chart) {
        if (!activeElements.length) return; // 点击空白区域不处理
        
        const elementIndex = activeElements[0].index;
        const targetLabel = chart.data.labels[elementIndex];
        
        // 重置所有图表的柱子为默认蓝色
        resetAllChartsColor();
        
        // 修改当前点击图表的目标柱子颜色
        chart.data.datasets[0].backgroundColor[elementIndex] = "red";
        chart.update();
        
        // 遍历第二个图表,找到所有同标签的柱子并修改颜色
        chart2.data.labels.forEach((label, idx) => {
          if (label === targetLabel) {
            chart2.data.datasets[0].backgroundColor[idx] = "red";
          }
        });
        chart2.update();
      }
    }
  });

  const ctx2 = document.getElementById('myChart2');
  chart2 = new Chart(ctx2, {
    type: 'bar',
    data: {
      labels: ['Mon', 'Thu', 'Wed', 'Thu', 'Fri', 'Sat'],
      datasets: [{
        label: '# of Votes',
        data: [8, 4, 4, 4, 4, 4],
        backgroundColor: ["blue", "blue", "blue", "blue", "blue", "blue"], 
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });

  // 重置所有图表的柱子颜色为默认蓝色
  function resetAllChartsColor() {
    // 重置chart1
    chart1.data.datasets[0].backgroundColor = chart1.data.datasets[0].backgroundColor.map(() => "blue");
    chart1.update();
    
    // 重置chart2
    chart2.data.datasets[0].backgroundColor = chart2.data.datasets[0].backgroundColor.map(() => "blue");
    chart2.update();
  }
</script>

代码说明

  1. 保存图表实例:用chart1和chart2变量存储创建的Chart实例,这样在点击事件里可以直接访问第二个图表的数据。
  2. 重置颜色函数:resetAllChartsColor方法统一将所有柱子恢复为蓝色,确保每次点击都是全新的高亮状态。
  3. 同标签匹配:通过forEach遍历第二个图表的labels,找到所有和点击标签相同的索引,修改对应位置的背景色。
  4. 图表更新:每次修改颜色后调用update(),让图表实时刷新显示新的颜色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:33:35