简体   繁体   中英

I can't change the color of the grids in Chart.js

I'm using Chartjs and I'm having problems with some properties, the page can be toggled in dark and light mode with a switch. I found how to change the color of the texts to be seen in dark mode with 'Chart.defaults.global.defaultFontColor' and it works fine, but when I try to change the color of the grids with 'Chart.defaults.scale.gridLines.color' it doesn't work, and no matter if I use 'Chart.defaults.scale.gridLines.display = false' or another grid's property, the lines don't change.

The grid does not change

I downloaded the Chart.js' js file and put it in the same folder as the project folder:

<script type="text/javascript" src="js/functions.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>

The chart I am using is the same as in the documentation: https://www.chartjs.org/docs/latest/getting-started/

This is the function associated with the switch:

function changeTheme() {
    var checkbox = document.getElementById('switch');
    if (checkbox.checked == true) {
        document.documentElement.setAttribute('data-theme', 'dark');
        localStorage.setItem('data-theme', 'dark');

        Chart.defaults.global.defaultFontColor = 'rgba(255,255,255,1)'; //This works fine
        Chart.defaults.scale.gridLines.color = 'rgba(255,255,255,1)'; //The line that should change the grid color

    }
    else {
        document.documentElement.setAttribute('data-theme', 'light');
        localStorage.setItem('data-theme', 'light');

        Chart.defaults.global.defaultFontColor = 'rgba(0,0,0,1)'; //This works fine
        Chart.defaults.scale.gridLines.color = 'rgba(0,0,0,1)'; //The line that should change the grid color

    }
    Chart.helpers.each(Chart.instances, function (instance) {
        instance.chart.update();
    });

    console.log(Chart);
}

Edit: I checked that the gridLines.color property does exist, and changes its value, but the chart is still not affected. Properties

Thanks!

add this in your options object but then with the correct color:

yAxes: [{
       gridLines: {
            color: 'red'
       },
}],
 xAxes: [{
      gridLines: {
            color: 'red'
      },
 }]

working example: https://jsfiddle.net/Leelenaleee/nfkwjvdq/2/

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