Skip to content

Instantly share code, notes, and snippets.

@supertommy
Last active April 12, 2020 18:25
Show Gist options
  • Save supertommy/bc728957ff7dcb8016da68b04d3a2768 to your computer and use it in GitHub Desktop.
Save supertommy/bc728957ff7dcb8016da68b04d3a2768 to your computer and use it in GitHub Desktop.
Phaser 3 WebFontFile for loading Web Fonts with WebFontLoader
import Phaser from 'phaser'
import WebFontLoader from 'webfontloader'
// https://photonstorm.github.io/phaser3-docs/Phaser.Loader.File.html
export default class WebFontFile extends Phaser.Loader.File
{
/**
* @param {Phaser.Loader.LoaderPlugin} loader
* @param {string | string[]} fontNames
* @param {string} [service]
*/
constructor(loader, fontNames, service = 'google')
{
super(loader, {
type: 'webfont',
key: fontNames.toString()
})
this.fontNames = Array.isArray(fontNames) ? fontNames : [fontNames]
this.service = service
this.fontsLoadedCount = 0
}
load()
{
const config = {
fontactive: (familyName) => {
this.checkLoadedFonts(familyName)
},
fontinactive: (familyName) => {
this.checkLoadedFonts(familyName)
}
}
switch (this.service)
{
case 'google':
config[this.service] = this.getGoogleConfig()
break
case 'adobe-edge':
config['typekit'] = this.getAdobeEdgeConfig()
break
default:
throw new Error('Unsupported font service')
}
WebFontLoader.load(config)
}
getGoogleConfig()
{
return {
families: this.fontNames
}
}
getAdobeEdgeConfig()
{
return {
id: this.fontNames.join(';'),
api: '//use.edgefonts.net'
}
}
checkLoadedFonts(familyName)
{
if (this.fontNames.indexOf(familyName) < 0)
{
return
}
++this.fontsLoadedCount
if (this.fontsLoadedCount >= this.fontNames.length)
{
this.loader.nextFile(this, true)
}
}
}
@plissken2013es
Copy link

You need a "break" after line 44.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment