【问题标题】:ChartJS - Labels backgroundChartJS - 标签背景
【发布时间】:2022-01-18 10:41:54
【问题描述】:

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

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

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

提前致谢。

【问题讨论】:

  • 你能在这里发布你的代码来澄清这个问题吗?
  • 我添加了一张描述问题的图片。

标签: javascript css background chart.js


【解决方案1】:

您可以在刻度上使用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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-13
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多