简体   繁体   中英

In ChartJS how do I change the color of a label in the legend?

I've got the following function making doughnut charts in ChartJS, the function imports the data, label text, and the id of the element. For some reason the options legend labels does not work for me. The default color of '#666' is not usable for my site's layout either.

my function:

function newDoughnutChart(id, labels, data) {
    var donutChartCanvas = $(id).get(0).getContext('2d')
    var donutData = {
        labels: labels,
        datasets: [
            {
                data: data,
                backgroundColor: backgroundColor,
            }
        ]
    }
    var donutOptions = {
        maintainAspectRatio: false,
        responsive: true,
        options: {
            legend: {
                labels: {
                    usePointStyle: true,
                    fontColor: "#fff",
                }
            }
        }
    }
    new Chart(donutChartCanvas, {
        type: 'doughnut',
        data: donutData,
        options: donutOptions
    })
}

backgroundColor is a variable I've set globally for this js file.

The legend config has been moved to the plugins section

Example:

 var options = { type: 'line', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], borderWidth: 1 }, { label: '# of Points', data: [7, 11, 5, 8, 3, 7], borderWidth: 1 } ] }, options: { plugins: { legend: { labels: { color: 'red' } } } } } 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.3.2/chart.js"></script> </body>

    var donutOptions = {
    maintainAspectRatio: false,
    responsive: true,
    options: {
        plugins: {
          legend: {
              display: true,
              labels: {
                  color: 'rgb(255, 99, 132)'
              }
          }
        }
      }
    }

You can change the color by grabbing the class of that div tag using CSS selector. But It's not the best idea because it will change the color in your whole app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM