Creating different font files and using web fonts

Exclusive offer: get 50% off this eBook here
Instant HTML5 Fonts and Typography [Instant]

Instant HTML5 Fonts and Typography [Instant] — Save 50%

Make your websites stand out by using custom fonts with splendid effects with this book and ebook

$12.99    $6.50
by Kharrat Jaouher | September 2013 | Web Services Web Development

In this article by Kharrat Jaouher, the author of Instant-HTML5 Fonts and Typography, the Creating different font files recipe will explain how to generate our own font and other cross-browser font files and the Using Web fonts recipe will cover web hosted fonts.

(For more resources related to this topic, see here.)

Creating different font files

In this recipe, we will learn how to create or get these fonts and how to generate the different formats for use in different browsers (Embedded Open Type, Open Type, True Type Font, Web Open Font Format, and SVG font) is explained in this recipe.

Getting ready

To get the original file of the font created during this recipe in addition to the generated font formats and the full source code of the project FontCreation; please refer to the receipe2 project folder.

How to do it...

The following steps are preformed for creating different font files:

  1. Firstly, we will get an original TTF font file. There are two different ways to get fonts:

    The first method is by downloading one from specialized websites. Both free and commercial solutions can be found with a wide variety of beautiful fonts.

    The following are a few sites for downloading free fonts: Google fonts, Font squirrel, Dafont, ffonts, Jokal, fontzone, STIX, Fontex, and so on. Here are a few sites for downloading commercial fonts: Typekit, Font Deck, Font Spring, and so on.

    We will consider the example of Fontex, as shown in the following screenshot. There are a variety of free fonts. You can visit the website at http://www.fontex.org/.

    The second method is by creating your own font and then generating a TIFF file format. There are a lot of font generators on the Web. We can find online generators or follow the professionals by scanning handwritten typography and finally import it to Adobe Illustrator to change it into vector based letters or symbols. For newbies, I recommend trying Fontstruct (http://fontstruct.com). It is a WYSIWYG flash editor that will help you create your first font file, as shown in the following screenshot:

    As you can see, we were trying to create the S letter using a grid and some different forms. After completing the font creation, we can now preview it rather than download the TTF file. The file is in the receipe2 project folder. The following screenshot is an example of a font we have created on the run:

  2. Now we have to generate the rest of file formats in order to ensure maximum compatibility with common browsers. We highly recommend the use of Font squirrel web font generator (http://www.fontsquirrel.com/tools/webfont-generator). This online tool helps to create fonts for @font-face by generating different font formats. All we need to do is to upload the original file (optionally adding same font variants bold, italic, or bold-italic), select the output formats, add some optimizations, and finally download the package. It is shown in the following screenshot:

  3. The following code explains the how to use this font:

    <!DOCTYPE html>
    <html>
    <head>
    <title>My first @font-face demo</title>
    <style type="text/css">
    @font-face {
    font-family: 'font_testregular';
    src: url('font_test-webfont.eot');
    src: url('font_test-webfont.eot?#iefix')
    format('embedded-opentype'),
    url('font_test-webfont.woff') format('woff'),
    url('font_test-webfont.ttf') format('truetype'),
    url('font_test-webfont.svg#font_testregular')
    format('svg');
    font-weight: normal;
    font-style: normal;
    }

    Normal font usage:

    h1 , p{
    font-family: 'font_testregular', Helvetica, Arial,
    sans-serif;
    }
    h1 {
    font-size: 45px;
    }
    p:first-letter {
    font-size: 100px;
    text-decoration: wave;
    }
    p {
    font-size: 18px;
    line-height: 27px;}
    </style>

    Font usage in canvas:

    <script src =
    "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/
    jquery.min.js" >
    </script>
    <script language="javascript" type="text/javascript">
    var x = 30, y = 60;
    function generate(){
    var canvas = $('canvas')[0],
    tx = canvas.getContext('2d');
    var t = 'font_testregular'; var c = 'red';
    var v =' sample text via canvas';
    ctx.font = '52px "'+t+'"';
    ctx.fillStyle = c;
    ctx.fillText(v, x, y);}
    </script>
    </head>
    <body onload="generate();">
    <h1>Header sample</h1>
    <p>Sample text with lettrine effect</p>
    <canvas height="800px" width="500px">
    Your browser does not support the CANVAS element.
    Try the latest Firefox, Google Chrome, Safari or Opera.
    </canvas>
    </body>
    </html>

How it works...

This recipe takes us through getting an original TTF file:

  • Font download: When downloading a font (either free or commercial) we have to pay close attention to terms of use. Sometimes, you are not allowed to use these fonts on the web and you are only allowed to use them locally.
  • Font creation: During this process, we have to pay attention to some directives.

    We have to create Glyphs for all the needed alphabets (upper case and lower case), numbers, and symbols to avoid font incompatibility.

    We have to take care of the spacing between glyphs and eventually, variations, and ligatures. A special creation process is reserved for right- to left-written languages.

  • Font formats generation: Font squirrel is a very good online tool to generate the most common formats to handle the cross-browser compatibility. It is recommended that we optimize the font ourselves via expert mode. We have the possibility of fixing some issues during the font creation such as missing glyphs, X-height matching, and Glyph spacing.
  • Font usage: We will go through the following font usage:

    Normal font usage:

    We used the same method as already adopted via font-family; web-safe fonts are also applied:

    h1 , p{
    font-family: 'font_testregular', Helvetica, Arial, sans-serif;
    }

    Font usage in canvas:

    The canvas is a HTML5 tag that renders dynamically, bitmap images via scripts Creating 2D shapes. In order to generate this image based on fonts, we will create the canvas tag at first. An alternative text will be displayed if canvas is not supported by the browser.

    <canvas height="800px" width="500px">
    Your browser does not support the CANVAS element.
    Try the latest Firefox, Google Chrome, Safari or Opera.
    </canvas>

    We will now use the jQuery library in order to generate the canvas output. An onload function will be initiated to create the content of this tag:

    <script
    src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/
    jquery.min.js" >
    </script>

    In the following function, we create a variable ctx which is a canvas occurrence of 2D context via canvas.getContext('2d'). We also define font-family using t as a variable, font-size, text to display using v as a variable, and color using c as a variable. These properties will be used as follows:

    <script language="javascript" type="text/javascript">
    var x = 30, y = 60;
    function generate(){
    var canvas = $('canvas')[0],
    ctx = canvas.getContext('2d');
    var t = 'font_testregular';
    var c = 'red' ;
    var v =' sample text via canvas';

    This is for font-size and family. Here the font-size is 52px and the font-family is font_testregular:

    ctx.font = '52px "'+t+'"';

    This is for color by fillstyle:

    ctx.fillStyle = c;

    Here we establish both text to display and axis coordinates where x is the horizontal position and y is vertical one.

    ctx.fillText(v, x, y);

Using Web fonts

In this recipe, you will learn how to use fonts hosted in distant servers for many reasons such as support services and special loading scripts.

A lot of solutions are widely available on the web such as Typekit, Google fonts, Ascender, Fonts.com web fonts, and Fontdeck. In this task, we will be using Google fonts and its special JavaScript open source library, WebFont loader.

Getting ready

Please refer to the project WebFonts to get the full source code.

How to do it...

We will get through four steps:

  1. Let us configure the link tag:

    <link rel="stylesheet" id="linker" type="text/css"
    href="http://fonts.googleapis.com/css?
    family=Mr+De+Haviland">

  2. Then we will set up the WebFont loader:

    <script type="text/javascript">
    WebFontConfig = {
    google: {
    families: [ 'Tangerine' ]
    }
    };
    (function() {
    var wf = document.createElement('script');
    wf.src = ('https:' == document.location.protocol ?
    'https' : 'http') +
    '://ajax.googleapis.com/ajax/libs/
    webfont/1/webfont.js';
    wf.type = 'text/javascript';
    wf.async = 'true';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(wf, s);
    })();
    </script>
    <style type="text/css">
    .wf-loading p#firstp {
    font-family: serif
    }
    .wf-inactive p#firstp {
    font-family: serif
    }
    .wf-active p#firstp {
    font-family: 'Tangerine', serif
    }

  3. Next we will write the import command:

    @import url(http://fonts.googleapis.com/
    css?family=Bigelow+Rules);

  4. Then we will cover font usage:

    h1 {
    font-size: 45px;
    font-family: "Bigelow Rules";
    }
    p {
    font-family: "Mr De Haviland";
    font-size: 40px;
    text-align: justify;
    color: blue;
    padding: 0 5px;}
    </style>
    </head>
    <body>
    <div id="container">
    <h1>This H1 tag's font was used via @import command </h1>
    <p>This font was imported via a Stylesheet link</p>
    <p id="firstp">This font was created via WebFont loader
    and managed by wf a script generated from webfonts.js.<br />
    loading time will be managed by CSS properties :
    <i>.wf-loading , .wf-inactive and .wf-active</i> </p>
    </div>
    </body>
    </html>

How it works...

In this recipe and for educational purpose, we used following ways to embed the font in the source code (the link tag, the WebFont loader, and the import command).

  • The link tag: A simple link tag to a style sheet is used referring to the address already created:

    <link rel="stylesheet" type="text/css"
    href="http://fonts.googleapis.com/
    css?family=Mr+De+Haviland">

  • The WebFont loader: It is a JavaScript library developed by Google and Typekit. It grants advanced control options over the font loading process and exceptions. It lets you use multiple web font providers.

    In the following script, we can identify the font we used, Tangerine, and the link to predefined address of Google APIs with the world google:

    WebFontConfig = {
    google: { families: [ 'Inconsolata:bold' ] }
    };

    We now will create wf which is an instance of an asynchronous JavaScript element. This instance is issued from Ajax Google API:

    var wf = document.createElement('script');
    wf.src = ('https:' == document.location.protocol ?
    'https' : 'http') +
    '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
    wf.type = 'text/javascript';
    wf.async = 'true';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(wf, s);
    })();

    We can have control over fonts during and after loading by using specific class names. In this particular case, only the p tag with the ID firstp will be processed during and after font loading.

    During loading, we use the class .wf-loading. We can use a safe font (for example, Serif) and not the browser's default page until loading is complete as follows:

    .wf-loading p#firstp {
    font-family: serif;
    }

    After loading is complete, we will usually use the font that we were importing earlier. We can also add a safe font for older browsers:

    .wf-active p#firstp {
    font-family: 'Tangerine', serif;
    }

  • Loading failure: In case we failed to load the font, we can specify a safe font to avoid falling in default browser's font:

    .wf-inactive p#firstp {
    font-family: serif;
    }

  • The import command: It is the easiest way to link to the fonts:

    @import url(http://fonts.googleapis.com/
    css?family=Bigelow+Rules);

  • Font usage: We will use the fonts as we did already via font-family property:

    h1 {
    font-family: "Bigelow Rules";
    }
    p {
    font-family: "Mr De Haviland";
    }

There's more...

The WebFont loader has the ability to embed fonts from mutiple WebFont providers. It has some predefined providers in the script such as Google, Typekit, Ascender, Fonts.com web fonts, and Fontdeck. For example, the following is the specific source code for Typekit and Ascender:

WebFontConfig ={
typekit: {
id: 'TypekitId'
}
};
WebFontConfig ={
ascender: {
key: 'AscenderKey',
families: ['AscenderSans:bold,bolditalic,italic,regular']
}
};

For the font providers that are not listed above, a custom module can handle the loading of the specific style sheet:

WebFontConfig = {
custom: {
families: ['OneFont', 'AnotherFont'],
urls: ['http://myotherwebfontprovider.com/stylesheet1.css',
'http://yetanotherwebfontprovider.com/stylesheet2.css' ]
}
};

For more details and options of the WebFont loader script, you can visit the following link:

https://developers.google.com/fonts/docs/webfont_loader

To download this API you may access the following URL:

https://github.com/typekit/webfontloader

How to generate the link to the font?

The URL used in every method to import the font in every method (the link tag, the WebFont loader, and the import command) is composed of the Google fonts API base url (http://fonts.googleapis.com/css) and the family parameter including one or more font names, ?family=Tangerine. Multiple fonts are separated with a pipe character (|) as follows:

?family=Tangerine|Inconsolata|Droid+Sans

Optionally, we can add subsets or also specify a style for each font:

Cantarell:italic|Droid+Serif:bold&subset=latin

Browser-dependent output

The Google fonts API serves a generated style sheet specific to the client, via the browser's request. The response is relative to the browser. For example, the output for Firefox will be:

@font-face {
font-family: 'Inconsolata';
src: local('Inconsolata'),
url('http://themes.googleusercontent.com/fonts/
font?kit=J_eeEGgHN8Gk3Eud0dz8jw') format('truetype');
}

This method lowers the loading time because the generated style sheet is relative to client's browser. No multiformat font files are needed because Google API will generate it, automatically.

Summary

In this way, we have learned how to create different font formats, such as Embedded Open Type, Open Type, True Type Font, Web Open Font Format, and SVG font, and how to use the different Web fonts such as Typekit, Google fonts, Ascender, Fonts.com web fonts, and Fontdeck.

Resources for Article:


Further resources on this subject:


Instant HTML5 Fonts and Typography [Instant] Make your websites stand out by using custom fonts with splendid effects with this book and ebook
Published: August 2013
eBook Price: $12.99
See more
Select your format and quantity:

About the Author :


Kharrat Jaouher

K. Jaouher is a web developer from Tunisia and has a degree in Software Engineer in 2007. Ever since, his objective was to improve his skills in multiple domains especially in web and industrial development. When he is not working on client projects he is often creating some new articles in his blog. He is also a mentor in different training centers in his country.

He, his wife, and his little baby girl make their home in Tunis city. He likes video games and music.

You can follow Jaouher on his blog at https://sites.google.com/site/webdevetipstuto or on his about me page at http://about.me/thabigboss/

Books From Packt


Instant Migration to HTML5 and CSS3 How-to [Instant]
Instant Migration to HTML5 and CSS3 How-to [Instant]

Learn HTML5 by Creating Fun Games
Learn HTML5 by Creating Fun Games

HTML5 Game Development with GameMaker
HTML5 Game Development with GameMaker

 Instant HTML5 Responsive Table Design How-to [Instant]
Instant HTML5 Responsive Table Design How-to [Instant]

HTML5 for Flash Developers
HTML5 for Flash Developers

 HTML5 and CSS3 Transition, Transformation and Animation
HTML5 and CSS3 Transition, Transformation and Animation

HTML5 Multimedia Development Cookbook
HTML5 Multimedia Development Cookbook

Instant HTML5 Presentations How-to [Instant]
Instant HTML5 Presentations How-to [Instant]


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software