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

如何为Chart.js添加自定义插件?自定义插件无输出问题排查

解决Chart.js自定义插件无响应的问题

你遗漏了自定义插件的注册步骤,Chart.js v4及以上版本要求所有自定义插件必须显式注册后才能被识别执行。

具体修改点:

  • 在创建Chart实例前,调用Chart.register()方法注册你的自定义插件
  • options.plugins里的空tooltipNote配置可留可删,不影响插件核心逻辑执行

修改后的完整代码:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.1.1/dist/chart.umd.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@2.1.1/dist/chartjs-plugin-annotation.min.js"></script>
</head>
<body>
  <div>
    <canvas id="myChart"></canvas>
  </div>

  <script>
    const ctx = document.getElementById('myChart');

    const tooltipNote = {
      id: 'tooltipNote',
      beforeDraw: chart => {
        console.log('chart');
      }
    }

    // 注册自定义插件
    Chart.register(tooltipNote);

    new Chart(ctx, {
      type: 'line',
      responsive: true,
      data: {
        labels: ['', '', '', '', '', ''],
        datasets: [{
          data: [42, 119, 53, 55, 62, 53],
        }]
      },
      options: {
        scales: {
          y: {
            suggestedMin: 0,
            offset: true
          },
        },
        plugins: {
          legend: {
            display: false
          },
        },
      },
    });
  </script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:15:49