I have a custom font (*.ttf
), that I am using to write text on the HTML canvas using Kinetic.js.
Unfortunately, on the first loading of the page it is not using my custom font, when reloading the page all is good.
Can I preload the font somehow?
I have tried this, but still not working:
<link rel="prefetch" href="resource/font/IDAutomationHC39M.ttf">
Can I tell Kinetic.js to preload it somehow?
The font is defined in my CSS like this:
@font-face {
font-family: "Barcode";
src: url(../font/IDAutomationHC39M.ttf);
}
Thanks in advance for your support!
I had the same problem with FontAwesome. Here is my solution:
No need to add an element to your page.
It usually works in all browsers, you just have to use font-face correctly. Just use a generator like this one: http://www.fontsquirrel.com/tools/webfont-generator
It creates a zip files with 4 font files (eot, svg, ttf, woff), and there is a css file with the necessary code:
I am using KineticJS, when i create the stage after page load it works with the correct font:
Should also be no problem if you don´t use Kinetic, of course.
If it does not work in some browsers, the font may not be loaded correctly. Using a timeout would be a bad workaround imho, you can try adding a hidden div right after the opening body tag:
It does not matter what you write there (it must not be empty though).
I am not working with Kinetic anymore, but this works great with the Phaser Engine.
I had a same problem today.. I ended up using this
After that you can do you normal KineticJS Stuff..! Actually its necessary to Load the Font first before using it..! I'm not good in English, but i hope u got my point. Also have a look at that link: Github Link
You could use this old css hack to force the font to be available:
Add a hidden element to the page that specifies Barcode font
And then in the CSS:
Finally, use jQuery to wait on the font to load before drawing text in your canvas.
Note: You might have to resort to $(window).load() in step#3 above to account for certain browsers async loading of fonts.
Via Google's webfontloader https://github.com/typekit/webfontloader
testStrings need to be used to determine whether or not a font with glyphs has loaded. If your font do not have glyphs or custom subsets, you do not need to use testStrings
May be it is late to answer but it's worth mentioning with a full example.
Please note that KonvaJS is derived from KeneticJS and is supported, but Keneticjs is not supported anymore.
Many thanks to @luschn for his great answer because as he stated: "timeout is bad solution".