Let's assume you have some fonts that you want to use for your application, stored under fonts/ directory. Your CSS file fonts.css will look something like this:
@font-face { font-family: "digital"; src: url('fonts/digital-7 (mono).ttf'); }
You will not need to make any changes to that file. Your html file may have looked something like this:
<body onload="myMain()"> <canvas id="mainCanvas" width="600" height="600"></canvas> </body>
You will have to change the html file to not load immediately because the issue arises from the browser's asynchronous loading of the font. This means that the font may not be ready when your javascript code finally runs. To call the myMain function only when the fonts load, we will use Google Web Font Loader. This way, the font will be pre-loaded and we can use that font in the canvas.
To do that, all you have to do is remove your call from the body's onload and add it to the activate callback from the WebFontConfig:
<script> // load fonts before loading the game WebFontConfig = { custom: { families: ['digital'], urls: ['fonts.css'] }, active: function() { myMain(); } }; </script> <script src="//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js"></script>
Make sure to put the two scripts in that order! This is important because you must first create the WebFontConfig object which the webfont.js script will look for. Putting it all together, your html file will look like this:
<!DOCTYPE html> <html lang="en-us"> <head> <meta charset="utf-8"> <title>HTML 5 WebApp</title> <script src="snake.js"></script> <script> // load fonts before loading the game WebFontConfig = { custom: { families: ['digital'], urls: ['fonts.css'] }, active: function() { myMain(); } }; </script> <script src="//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js"></script> </head> <body> <canvas id="mainCanvas" width="600" height="600"></canvas> </body> </html>