Last active
April 12, 2020 18:25
-
-
Save supertommy/bc728957ff7dcb8016da68b04d3a2768 to your computer and use it in GitHub Desktop.
Phaser 3 WebFontFile for loading Web Fonts with WebFontLoader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need a "break" after line 44.