【问题标题】:I can't change the color of the grids in Chart.js我无法更改 Chart.js 中网格的颜色
【发布时间】:2021-01-30 05:50:22
【问题描述】:

我正在使用 Chartjs,但我遇到了一些属性问题,可以使用开关在深色和浅色模式下切换页面。我发现如何使用“Chart.defaults.global.defaultFontColor”更改要在暗模式下看到的文本颜色,并且效果很好,但是当我尝试使用“Chart.defaults.scale”更改网格的颜色时。 gridLines.color' 它不起作用,无论我使用'Chart.defaults.scale.gridLines.display = false' 还是其他网格的属性,线条都不会改变。

The grid does not change

我下载了Chart.js的js文件,和项目文件夹放在同一个文件夹里:

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

我使用的图表与文档中的相同:https://www.chartjs.org/docs/latest/getting-started/

这是与开关相关的功能:

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);
}

编辑: 我检查了 gridLines.color 属性确实存在,并更改了它的值,但图表仍然没有受到影响。 Properties

谢谢!

【问题讨论】:

  • 我没用过这个lib所以可能是错的,但是渲染完图表后改全局设置也没关系,要update it,可以看您编写代码以更改默认值的工作here。我不知道如何更新它,所以我不会发布答案。祝你好运。
  • @Gunther 很奇怪,您在 jsfiddle 中输入的代码可以正常工作,但是当尝试使用通用函数复制它时却不行。我所做的是检查主题,一旦分配,分配颜色并重新加载页面,它不是最好的,但这样它就可以了。

标签: javascript chart.js


【解决方案1】:

将此添加到您的选项对象中,然后使用正确的颜色:

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

工作示例:https://jsfiddle.net/Leelenaleee/nfkwjvdq/2/

【讨论】:

  • 有可能,我的想法不是修改每个图表的数据集(因为数据集必须在一种颜色和另一种颜色之间交替),而是在以下情况下使用全局属性改变主题。但是如果我找不到其他方法,我将不得不像这样使用它。谢谢!
猜你喜欢
  • 2021-08-14
  • 2023-03-21
  • 2020-09-13
  • 2015-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
相关资源
最近更新 更多