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

Chart.js 4.4.2本地库搭配annotation插件无法显示矩形的问题求助

解决Chart.js 4.4.2 + chartjs-plugin-annotation 1.0.3本地库矩形注释不显示的问题

问题核心原因

你之前使用的CDN是Chart.js 2.x + 旧版annotation插件,而Chart.js 4.x与v1.x的annotation插件在配置结构、插件注册逻辑上完全不同:

  • 旧版annotation直接挂载在options下,v4.x需放在options.plugins.annotation中
  • 注释定义从数组改为键值对对象(每个注释需要唯一ID)
  • Chart.js 4.x不再自动全局注册插件,需手动执行注册操作
  • v4.x默认的轴ID为"x"/"y",而非旧版的"x-axis-0"/"y-axis-0"

完整本地库可用示例

<!DOCTYPE html>
<html>
<head>
    <title>Chart.js Annotation Demo</title>
</head>
<body>
    <canvas id="tempChart" width="800" height="400"></canvas>

    <!-- 引入本地库文件(确保文件路径与项目实际结构一致) -->
    <script src="javascript/chartjs/chart.umd.js"></script>
    <script src="javascript/chartjs-plugin-annotation/chartjs-plugin-annotation.min.js"></script>

    <script>
        // 手动注册annotation插件(v4.x必须步骤)
        Chart.register(ChartAnnotation);

        const tempData = {
            labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            datasets: [{
                label: 'Temp',
                fill: false,
                data: [-5, 0, 5, -10, -5, 12, 15, 20, 15, 10, 5, 0],
                borderColor: '#2c3e50'
            }]
        };

        const chartOptions = {
            plugins: {
                // 修正:annotation配置放在plugins节点下
                annotation: {
                    annotations: {
                        // 修正:注释改为键值对形式,需设置唯一ID
                        tempRangeBox: {
                            drawTime: "beforeDatasetsDraw",
                            type: "box",
                            xScaleID: "x", // v4.x默认x轴ID
                            yScaleID: "y", // v4.x默认y轴ID
                            borderWidth: 0,
                            yMin: 18,
                            yMax: 32,
                            backgroundColor: "rgba(46, 204, 113, 0.3)"
                        }
                    }
                }
            },
            scales: {
                y: {
                    // 确保y轴范围覆盖注释区域,避免注释被隐藏
                    min: -15,
                    max: 35
                }
            }
        };

        const chartConfig = {
            type: 'line',
            options: chartOptions,
            data: tempData,
        };

        // 初始化图表
        const ctx = document.getElementById('tempChart').getContext('2d');
        new Chart(ctx, chartConfig);
    </script>
</body>
</html>

关键修正点说明

  1. 插件注册:必须添加Chart.register(ChartAnnotation);,否则插件无法生效
  2. 配置结构:将annotation移至options.plugins下,注释改为带唯一ID的键值对
  3. 轴ID修正:使用v4.x默认的轴ID"x"/"y"替代旧版命名
  4. 轴范围调整:显式设置y轴的min和max,确保注释区域在可视范围内

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:15:14