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

Chart.js 2.9.4固定水平线添加失败求助

在Chart.js 2.9.4中添加固定水平线的解决方案

你的代码存在三个核心问题,导致水平线无法显示,以下是修正后的完整代码及问题说明:

问题分析

  1. 插件注册方式错误:Chart.js 2.x 不支持在配置的options.plugins中直接传入自定义插件,必须通过Chart.pluginService.register()完成注册。
  2. 线条绘制逻辑错误:strokeRect的height设为0时无法渲染出可见线条,改用路径绘制API才能画出完整的水平线。
  3. 轴实例获取错误:2.x版本中默认y轴的ID是y-axis-0,需要通过该ID从chart.scales中获取轴实例,而非直接解构scales.y。

修正后的完整代码

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    * {
      margin: 0;
      padding: 0;
      font-family: sans-serif;
    }
    
    .chartMenu {
      width: 100vw;
      height: 40px;
      background: #1A1A1A;
      color: rgba(54, 162, 235, 1);
    }
    
    .chartMenu p {
      padding: 10px;
      font-size: 20px;
    }
    
    .chartCard {
      width: 100vw;
      height: calc(100vh - 40px);
      background: rgba(54, 162, 235, 0.2);
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .chartBox {
      width: 700px;
      padding: 20px;
      border-radius: 20px;
      border: solid 3px rgba(54, 162, 235, 1);
      background: white;
    }
  </style>
</head>

<body>
  <div class="chartCard">
    <div class="chartBox">
      <canvas id="myChart"></canvas>
    </div>
  </div>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
  <script>
    // setup 
    const data = {
      labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      datasets: [{
        label: 'Weekly Sales',
        data: [18, 12, 6, 9, 12, 3, 9],
        backgroundColor: [
          'rgba(255, 26, 104, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(0, 0, 0, 0.2)'
        ],
        borderColor: [
          'rgba(255, 26, 104, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(0, 0, 0, 1)'
        ],
        borderWidth: 1
      }]
    };

    // 注册自定义插件
    Chart.pluginService.register({
      id: 'horizontalLine',
      afterDraw: function(chart) {
        const ctx = chart.chart.ctx;
        const chartArea = chart.chartArea;
        const yAxis = chart.scales['y-axis-0'];
        
        // 水平线对应的数值
        const targetValue = 12;
        const yPixel = yAxis.getPixelForValue(targetValue);
        
        ctx.save();
        ctx.strokeStyle = 'green';
        ctx.lineWidth = 2;
        // 绘制水平线
        ctx.beginPath();
        ctx.moveTo(chartArea.left, yPixel);
        ctx.lineTo(chartArea.right, yPixel);
        ctx.stroke();
        ctx.restore();
      }
    });

    // config 
    const config = {
      type: 'line',
      data: data,
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    };

    const myChart = new Chart(
      document.getElementById('myChart'),
      config
    );
  </script>

</body>

</html>

关键修改说明

  • 用Chart.pluginService.register()注册插件,适配2.x版本的插件机制。
  • 使用beginPath()、moveTo()、lineTo()绘制完整水平线,替代无效的strokeRect调用。
  • 通过chart.scales['y-axis-0']获取y轴实例,确保正确计算目标数值对应的像素位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 22:17:48