Using Web fonts

Chart.js can use any fonts that are available for your website. Besides the standard fonts supported by all browsers (serif, sans-serif, monospace), you can also use online fonts loaded by a style sheet.

In the following example, we are using a free web font (OFL license), called Yanone Kaffeesatz, obtained from Google Fonts. To install it, simply load the CSS by adding the following link to the <head> of your HTML page:

<link href="https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz"
rel="stylesheet">

Now you can use the Yanone Kaffeesatz font family in CSS and HTML. Canvas can set it as the context font, using the font property. The simplest way to use it in Chart.js is to declare it as the default global font. You can also configure any font styles if this feature is available:

Chart.defaults.global.defaultFontFamily = '"Yanone Kaffesatz", sans-serif';

In the following example, we changed several font properties (family, color, size, and style), using global options from one of the pie/doughnut charts that were created in the last chapter:

Chart.defaults.global.defaultFontColor = 'black';
Chart.defaults.global.defaultFontFamily =
'"Yanone Kaffesatz", "Helvetica Narrow", "Arial Narrow", sans-serif';
Chart.defaults.global.defaultFontSize = 24;
Chart.defaults.global.defaultFontStyle = 'normal';
Chart.defaults.global.title.fontSize = 40;
Chart.defaults.global.title.fontColor = 'hsla(240,50%,70%,1)';
Chart.defaults.global.legend.labels.fontColor = 'hsla(120,20%,60%,1)';

The result is shown in the following diagram. The code is available in Fonts/fonts-1.html and requires the installing of the Yanone Kaffesatz font (or any other font, if you edit the code):

A doughnut chart using a web font for titles and labels. Code: Fonts/fonts-1.html.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset