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

Chart.js折线图无法同时启用annotation插件与scales配置求助

Chart.js折线图:同时启用Annotation色块与Scales配置的解决方案

你的问题出在options的结构配置错误:注释掉的scales配置块里,你直接把chartPlugins作为options的一个属性,而非将其内部的plugins配置合并到options中,导致Annotation插件无法正确读取到注释色块的配置。

修正后的完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <title>ChartT1</title>
</head>
<body>
<div  id="TC1">
    <canvas id="ChartT1"></canvas>
</div>

<script src='https://cdn.jsdelivr.net/npm/chart.js@^4'></script>
<script src='https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@^3'></script>

<script>

var wwtemp   = [ 42.2, 42.4, 43.2, 45.1, 46.5, 48.7, 49.4, 50.5, 49.9, 49.2 ];
var tempdata = [ 12.3, 13.5, 14.6, 15.3, 16.3, 15.3, 14.6, 13.7, 11.8, 10.7 ];
var timeaxis = ['12:10','12:15','12:20','12:25','12:30','12:35','12:40','12:45','12:50','12:55'];

const chartConfig = {
    type: 'line',
    data: {
        labels: timeaxis,
        datasets: [ {
            label: 'Temperature (°C)',
            data: tempdata,
            borderColor: 'blue',
            borderWidth: 1,
            pointStyle: 'line',
            radius: 0,
        },
        {
            label: 'WW-Temp (°C)',
            data: wwtemp,
            borderColor: 'red',
            borderWidth: 1,
            pointStyle: 'line',
            radius: 0,
        } ],
    },
    options: {
        responsive: true,
        aspectRatio: 1,
        maintainAspectRatio: true,
        scales: {
            x: { 
                ticks: { 
                    maxRotation: 80,
                    minRotation: 80,
                },
            },
            y: { 
                beginAtZero: false,
                min: -10,
                max: 60,
                ticks:{ stepSize: 10, }
            }
        },
        plugins: {
            annotation: {
                annotations: {
                    box1: {
                        type: 'box',
                        yMin: 42,
                        yMax: 50,
                        borderWidth: 0,
                        backgroundColor: 'rgba(204, 255, 153, 0.3)'
                    }
                }
            }
        }
    }
}

const ctx = document.getElementById('ChartT1').getContext('2d');
const chart = new Chart(ctx, chartConfig);

</script>

</body>
</html>

关键修改说明

  • 将原来chartPlugins中的Annotation配置直接合并到options.plugins下,与scales同级,确保Chart.js能同时读取到坐标轴配置和插件配置。
  • 移除了单独的chartPlugins变量,将配置内联到options中(也可以通过对象合并方式保留chartPlugins,比如options: {...chartPlugins.plugins, responsive: true, ...},但内联方式更直观)。

修改后,42-50区间的绿色色块会正常显示,同时x轴刻度旋转、y轴范围等scales配置也会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 17:54:59