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

Chart.js 4.x中annotation插件@3版本垂直标线标签丢失求助

解决chartjs-plugin-annotation@3版本垂直标线标签消失问题

chartjs-plugin-annotation从v1升级到v3后,API配置存在破坏性变更,标签消失的核心原因是标签的配置字段和结构发生了变化,以下是具体修复方案:

关键变更点

  • v3中标签启用字段从enabled: true改为display: true
  • 标签的位置需要显式配置,否则可能默认处于画布外导致不可见
  • 插件CDN需要切换到v3版本

修复后的完整代码

<!DOCTYPE html>
<html>
<head>
  <title>Chart.js Line Chart with Annotations</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
  <!-- 切换到annotation插件v3版本 -->
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@3"></script>
</head>
<body>
    <p>plugin-annotation@3 - labels fixed</p>
    <canvas id="myChart" width="400" height="200"></canvas>
<script>
    const labels = Array.from({ length: 35 }, (_, i) => (i + 1).toString());
    const dataPoints = labels.map(label => Math.random() * 100);

    const data = {
      labels: labels,
      datasets: [{
        label: 'Sample Data',
        data: dataPoints,
        borderColor: 'blue',
        fill: false
      }]
    };

    const config = {
      type: 'line',
      data: data,
      options: {
        scales: {
          x: { beginAtZero: true },
          y: { beginAtZero: true }
        },
        plugins: {
          annotation: {
            annotations: genVertLines(labels)
          }
        }
      }
    };

    function genVertLines(labels) {
      return labels.filter(label => label.endsWith('3')).map((label) => ({
          type: 'line',
          mode: 'vertical',
          scaleID: 'x',
          value: label,
          borderColor: 'red',
          borderWidth: 2,
          label: {
            content: `Label-${label}`,
            // v3中启用标签用display而非enabled
            display: true,
            // 配置标签位置:顶部,向上偏移10px避免和图表重叠
            position: 'top',
            yAdjust: -10,
            // 可选:设置标签样式增强可读性
            backgroundColor: 'rgba(255,0,0,0.8)',
            color: '#fff',
            padding: 4
          }
        }));
    }

    window.onload = function() {
      const ctx = document.getElementById('myChart').getContext('2d');
      new Chart(ctx, config);
    };
  </script>
</body>
</html>

额外说明

  • 如果需要调整标签的水平位置,可以添加xAdjust字段
  • 标签的content支持字符串、数组或回调函数,可根据需求动态生成内容
  • v3版本还支持更多样式配置(如字体、边框等),可根据需要扩展

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 04:57:08