ChartJS - 标签背景

ChartJS - Labels background

我正在使用 Chart.js 绘制一个简单的折线图。 XAxis Labels和YAxis Labels区域如何设置背景颜色?

折线图的文档在这里:https://www.chartjs.org/docs/2.7.3/getting-started/?h=line,但我找不到任何相关信息。

这是我要应用背景色的区域:

提前致谢。

您可以在比例尺上使用backgroundColor中的构建,这种方法只对chartArea下的部分进行着色:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {
    scales: {
      y: {
        backgroundColor: 'red'
      },
      x: {
        backgroundColor: 'yellow'
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.js"></script>
</body>

如果你真的想要所有的长度,你需要编写一个自定义插件:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {
    plugins: {
      scaleBackground: {
        x: 'red',
        y: 'yellow',
        drawXOverY: true
      }
    }
  },
  plugins: [{
    id: 'scaleBackground',
    beforeDraw: (chart, args, opts) => {
      const {
        scales: {
          x,
          y
        },
        ctx,
        chartArea: {
          left
        },
        canvas
      } = chart;

      if (opts.drawXOverY) {
        ctx.fillStyle = opts.y || 'transparent';
        ctx.fillRect(0, 0, left, canvas.height);

        ctx.fillStyle = opts.x || 'transparent';
        ctx.fillRect(0, x.top, canvas.width, x.bottom);
      } else {
        ctx.fillStyle = opts.x || 'transparent';
        ctx.fillRect(0, x.top, canvas.width, x.bottom);

        ctx.fillStyle = opts.y || 'transparent';
        ctx.fillRect(0, 0, left, canvas.height);
      }


    }
  }]
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.js"></script>
</body>