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

如何将Chart.js图表的缩放选择器置于图表前端?

Chart.js缩放选择器被图表遮挡,无法操作的解决方法

问题描述

我使用Chart.js制作了一张用于计算两条折线间区域的散点图,希望通过缩放选择器对该图表进行缩放操作,但目前缩放选择器处于图表区域后方,无法正常操作,请问如何将其置于图表上方?

当前效果:
当前效果

当前构建图表的代码:

const myChart = new Chart(ctx, {
        type: 'scatter',
        data: {
          datasets: [{
            label: 'linha 1',            
            data:[
              {x: -11, y: 7},
              {x: -11, y: 7},
              {x: 3, y: 8},
            ],
            fill: '+1',
            showLine: true,
            borderColor: '#009999',
            backgroundColor: '#009999',
          }, 
          {
            label: 'linha 2',
            data: [
              {x: 0, y: 7},
              {x: 0, y: 7},
              {x: 8, y: 8},
            ],
            borderColor: '#f00',
            showLine: true,
            backgroundColor: '#f00',
          }
        ]
        },
        options: {         
          plugins: {
            zoom: {
              zoom: {
                mode: 'xy',
                drag: {
                  enabled: true,
                  borderColor: 'rgb(54, 162, 235)',
                  borderWidth: 1,
                  backgroundColor: 'rgba(54, 162, 235, 0.3)'
                }
              }
              
            },
          },
        }
    });

解决方法

方法1:通过插件配置设置层级(推荐)

在zoom插件的drag配置项中添加zIndex属性,将其值设为高于图表画布的数值(例如10),就能让缩放选择器显示在图表上方:

修改后的配置代码片段:

options: {         
  plugins: {
    zoom: {
      zoom: {
        mode: 'xy',
        drag: {
          enabled: true,
          borderColor: 'rgb(54, 162, 235)',
          borderWidth: 1,
          backgroundColor: 'rgba(54, 162, 235, 0.3)',
          zIndex: 10 // 新增:提升缩放选择器的层级
        }
      }
    },
  },
}

方法2:通过CSS强制调整层级

如果配置方式不生效,可以直接用CSS修改插件生成的选择器元素层级:

.chartjs-zoom-selection {
  z-index: 10 !important;
}

chartjs-zoom-selection是插件默认给拖拽选择元素添加的类名,设置更高的z-index即可让它覆盖在图表之上。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:50:28