Reputation: 1564
I have a font in a fonts/
directory. How do I load this into the game, then use it on a text object in my game? I haven't been able to find anything on using fonts in Phaser 3.
Upvotes: 13
Views: 16783
Reputation: 1250
For Phaser 3 there is a good official example for Custom Webfont
This comes down to:
preload () {
this.load.script('webfont', 'https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js');
}
create () {
WebFont.load({
custom: {
families: [ 'troika' ]
},
active: function () {
this.add.text(32, 32, 'The face of the\nmoon was in\nshadow.', { fontFamily: 'troika', fontSize: 80, color: '#ff0000' }).setShadow(2, 2, '#333333', 2, false, true);
}
});
}
Upvotes: 1
Reputation: 903
Here's a small function I made, which only requires the font name and url:
function loadFont(name, url) {
var newFont = new FontFace(name, `url(${url})`);
newFont.load().then(function (loaded) {
document.fonts.add(loaded);
}).catch(function (error) {
return error;
});
}
And use it like:
loadFont("mixolydian", "assets/fonts/mixolydian.ttf");
That's it! You can now use your custom font in Phaser. All you have to do is change the fontFamily
value to your new font name (i.e. mixolydian).
Upvotes: 14
Reputation: 2564
First use css to load your font(@fontface):
<style media='screen' type='text/css'>
@font-face {
font-family: font1;
src: url('media/yourfont.ttf');
font-weight:400;
font-weight:normal;
}
</style>
And then use a div
to load your font:
<div style="font-family:font1; position:absolute; left:-1000px; visibility:hidden;">.</div>
Now you can put it in add it in your game:
this.add.text(190, 136, 'text', {
fontFamily: 'font1',
});
Upvotes: 32