Javascript 如何更改 Chart.JS 中标签的字体(系列)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39603447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:43:44  来源:igfitidea点击:

How can I change the font (family) for the labels in Chart.JS?

javascriptjqueryhtmlcsschart.js2

提问by B. Clay Shannon

I want to change the font to something snazzier in my Chart.JS horizontal bar chart. I've tried the following, but none of it works:

我想在我的 Chart.JS 水平条形图中将字体更改为更时髦的字体。我尝试了以下方法,但都不起作用:

var optionsBar = {
    . . .
    //fontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
    //bodyFontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
    //bodyFontFamily: "'Candara'"
    label: {
        font: {
            family: "Georgia"
        }
    }
};

I also read that this would work:

我还读到这会起作用:

Chart.defaults.global.defaultFont = "Georgia"

...but where would this code go, and how exactly should it look? I tried this:

...但是这段代码会去哪里,它究竟应该是什么样子?我试过这个:

priceBarChart.defaults.global.defaultFont = "Georgia";

...but also to no good effet.

...但也没有什么好效果。

For the full picture/context, here is all the code that makes up this chart:

对于完整的图片/上下文,以下是构成此图表的所有代码:

HTML

HTML

<div class="chart">
    <canvas id="top10ItemsChart" class="pie"></canvas>
    <div id="pie_legend"></div>
</div>

JQUERY

查询

    var ctxBarChart = 
$("#priceComplianceBarChart").get(0).getContext("2d");
    var barChartData = {
        labels: ["Bix Produce", "Capitol City", "Charlies Portland", 
"Costa Fruit and Produce", "Get Fresh Sales",
"Loffredo East", "Loffredo West", "Paragon", "Piazza Produce"],
        datasets: [
            {
                label: "Price Compliant",
                backgroundColor: "rgba(34,139,34,0.5)",
                hoverBackgroundColor: "rgba(34,139,34,1)",
                data: [17724, 5565, 3806, 5925, 5721, 6635, 14080, 9027, 
25553]
            },
            {
                label: "Non-Compliant",
                backgroundColor: "rgba(255, 0, 0, 0.5)",
                hoverBackgroundColor: "rgba(255, 0, 0, 1)",
                data: [170, 10, 180, 140, 30, 10, 50, 100, 10]
            }
        ]
    }

    var optionsBar = {
        scales: {
            xAxes: [{
                stacked: true
            }],
            yAxes: [{
                stacked: true
            }]
        },
        //fontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
        //bodyFontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
        //bodyFontFamily: "'Candara'"
        //Chart.defaults.global.defaultFont = where does this go?
        label: {
            font: {
                family: "Georgia"
            }
        }
    };

    var priceBarChart = new Chart(ctxBarChart, {
        type: 'horizontalBar',
        data: barChartData,
        options: optionsBar
    });
    //priceBarChart.defaults.global.defaultFont = "Georgia";

I even tried this:

我什至试过这个:

CSS

CSS

.candaraFont13 {
    font-family:"Candara, Georgia, serif";
    font-size: 13px;
}

HTML

HTML

<div class="graph_container candaraFont13">
    <canvas id="priceComplianceBarChart"></canvas>
</div>

...but I reckon the canvas drawing takes care of the font appearance, as adding this made no difference.

...但我认为画布绘图会处理字体外观,因为添加它没有任何区别。

UPDATE

更新

I tried this and it completely broke it:

我试过了,它完全打破了它:

Chart.defaults.global = {
    defaultFontFamily: "Georgia"
}

UPDATE 2

更新 2

As Matthew intimated, this worked (before any of the chart-specific script):

正如马修暗示的那样,这有效(在任何特定于图表的脚本之前):

Chart.defaults.global.defaultFontFamily = "Georgia";

回答by Matthew Campbell

This should be useful: http://www.chartjs.org/docs/. It says "There are 4 special global settings that can change all of the fonts on the chart. These options are in Chart.defaults.global".

这应该很有用:http: //www.chartjs.org/docs/。它说“有 4 个特殊的全局设置可以更改图表上的所有字体。这些选项位于Chart.defaults.global”中。

You'll need to change defaultFontFamilyfor the font. And defaultFontColor, defaultFontSize, and defaultFontStylefor color, size, etc.

您需要更改defaultFontFamily字体。和defaultFontColordefaultFontSize、 和defaultFontStyle颜色、大小等。

回答by Super Model

Change font size,color,family and weight using chart.js

使用 chart.js 更改字体大小、颜色、系列和粗细

scales: {
        yAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}],
        xAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}]
        }

See Full code

查看完整代码

<head>
    <title>Chart.js</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
    <script src="js/Chart.bundle.js"></script>
    <script src="js/utils.js"></script>
    <style>
        canvas {
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            font-weight:700;  
        }
    </style>
</head>
<body>
    <div id="container" style="width:70%;">
        <canvas id="canvas"></canvas>
    </div>
    <script>
        var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        var color = Chart.helpers.color;
        var barChartData = {
            labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
            datasets: [{
                    label: 'Completed',
                    // Green
                    backgroundColor: '#4caf50',
                    borderColor: '#4caf50',
                    borderWidth: 1,
                    data: [
                        5, 15, 25, 35, 45, 55
                    ]
                }, {
                    label: 'Created',
                    // Blue
                    backgroundColor: '#1976d2',
                    borderColor: '#1976d2',
                    borderWidth: 1,
                    data: [
                        10, 20, 30, 40, 50, 60
                    ]
                }]

        };

        window.onload = function () {
            var ctx = document.getElementById("canvas").getContext("2d");
            window.myBar = new Chart(ctx, {
                type: 'bar',
                data: barChartData,
                options: {
                    responsive: true,
                    legend: {
                        position: 'top',
                        onClick: null
                    },

                    title: {
                        display: true,
                        text: '',
                        fontSize: 20
                    },
                    scales: {
                        yAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}],
                        xAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}]
                    }
                }
            });
        };
    </script>
</body>

回答by matoneski

If you wanted to add the font-family to the chart object then you can add it in the options object.

如果要将字体系列添加到图表对象,则可以将其添加到选项对象中。

options: {
  legend: {
    labels: { 
      fontFamily: 'YourFont'
    }
  }...}

Here is a link to the docs: https://www.chartjs.org/docs/latest/general/fonts.html

这是文档的链接:https: //www.chartjs.org/docs/latest/general/fonts.html

回答by Gust van de Wal

You named the chart priceBarChart in the following part of your code:

您在代码的以下部分将图表命名为 priceBarChart:

var priceBarChart = new Chart(ctxBarChart, {
  type: 'horizontalBar',
  data: barChartData,
  options: optionsBar
})

Which means that priceBarChart.defaults.global.defaultFont = 'Georgia'will 'dive' into the variable priceBarChart, go into its default properties, change one of its global properties and that one is defaultFont, exactly what you want.

这意味着priceBarChart.defaults.global.defaultFont = 'Georgia'将“潜入”变量 priceBarChart,进入其默认属性,更改其全局属性之一,该属性是 defaultFont,正是您想要的。

But when you apply this code, you basically create the chart with the wrong font and then change it again, which is a bit ugly. What you need to do is tell the chart what the font is beforehand.

但是当你应用这段代码时,你基本上是用错误的字体创建图表,然后再次更改它,这有点难看。你需要做的是事先告诉图表字体是什么。

You do this by merging your font declaration with the rest of the options, just like how you did it with your variables barChartDataand optionsBar.

您可以通过将字体声明与其余选项合并来完成此操作,就像您对变量barChartDataoptionsBar.

After you've created barChartDataand optionsBar, create another variable with the name, let's say, defaultOptions, like so:

创建barChartDataand 后optionsBar,创建另一个名称为 的变量,例如,defaultOptions,如下所示:

var defaultOptions = {
    global: {
        defaultFont: 'Georgia'
    }
}

You can see that it has the same structure. You go into the global options, and change its defaultFont property. Now you need to apply it to the created chart at the moment it is created, like so:

您可以看到它具有相同的结构。您进入全局选项,并更改其 defaultFont 属性。现在,您需要在创建图表时将其应用于创建的图表,如下所示:

var priceBarChart = new Chart(ctxBarChart, {
  type: 'horizontalBar',
  data: barChartData,
  options: optionsBar,
  defaults: defaultOptions //This part has been added
})

This method of overwriting options is what is being used in almost every JavaScript plugin. When you create a newinstance, the plugin copies an object that contains objects that contain objects and so forth. But these objects can be modified with additional options, like barChartData, optionsBarand defaultOptions.

几乎每个 JavaScript 插件都使用这种覆盖选项的方法。创建new实例时,插件会复制一个包含对象的对象,该对象包含对象等等。但是这些对象可以使用其他选项进行修改,例如barChartDataoptionsBardefaultOptions

I hope this helps!

我希望这有帮助!