我怎样才能在图表 js 中给完整的图例一个背景颜色?

How can i give the full Legend a background color in chart js?

我正在做一个项目,我们正在使用用图表 js 创建的图表。我想给图例一个背景颜色(图像中绘制的顶部)。在互联网上进行了大量搜索后,我仍然没有找到解决问题的方法,所以我想让我们尝试堆栈溢出。有人可以帮帮我吗??>!

the part i want to give a background color

这是我的部分代码

enter code here 
<div>
  <canvas id="myChart"></canvas>
</div>
 
<script>
  const labels = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
];
const data = {
  labels: labels,
  datasets: [{
    label: 'My First dataset',
    backgroundColor: 'rgb(255, 99, 132)',
    borderColor: 'rgb(255, 99, 132)',
    data: [0, 10, 5, 2, 20, 30, 45],
  }]
};
  
  const config = {
  type: 'line',
  data: data,
  options: {}
};
  
  var myChart = new Chart(
    document.getElementById('myChart'),
    config
  );
</script>

您可以为此使用自定义插件:

const plugin = {
  id: 'legendBackground',
  beforeDraw: (chart, args, opts) => {
    const {
      chartArea: {
        width,
        top,
        left
      },
      ctx
    } = chart;
    ctx.fillStyle = opts.color || 'transparent';
    ctx.fillRect(left, 0, width, top)
  }
}

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderColor: 'orange'
    }]
  },
  options: {
    plugins: {
      legendBackground: {
        color: 'pink'
      }
    }
  },
  plugins: [plugin]
}

const 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.7.1/chart.js"></script>
</body>