[Chartjs]-ChartJS โ€“ Labels background

1๐Ÿ‘

โœ…

You can use the build in backgroundColor on the scale, this approach only colors the part under the 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>

If you really want all the length you will need to write a custom plugin:

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>

Leave a comment