How do I dynamically load fonts from a web server?

Viewed 223

I need to dynamically load custom parametric fonts for a project. The fonts are coming from a web server I wrote, which takes input parameters via url and sends back an OTF file via Express. I've been trying to write the client side, but I've been having a lot of trouble.

For background, the web server routes anything from localhost:1999/font/ to makeFont(). It draws the font parameters from the url, so localhost:1999/font/43-64-24-63 returns a font with parameter values [43,64,24,63]. There are 16 parameters in reality, and the web server will eventually be hosted at a real URL, but neither of those seem important at the moment. The server generates the font and saves the file locally, then sends it back via Express's sendFile(). It's currently saving as an OTF, but I can save it as another format if need be.

I started with these tutorials:

and worked through a couple of other issues (FontFace and its ilk need to be ambiently declared, etc.). I now run into one of the following issues:

If I try to load a font via var junction_font = new FontFace('Junction Regular', 'url(fonts/junction-regular.woff)');, I get the following error:

Failed to decode downloaded font: http://localhost:1234/fonts/junction-regular.woff \n OTS parsing error: invalid version tag

To clarify, I downloaded an actual copy of Junction Regular's .woff and saved it in a /fonts folder in the same directory as my index.html and index.ts files.

Meanwhile, if I try to load a file directly via a real URL (I used one from a Google Fonts link), I get this error:

var junction_font = new FontFace('Junction Regular', 'https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap');

Failed to load font: SyntaxError: The source provided ('https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap') could not be parsed as a value list.

I also tried it on the latin WOFF2 download link at https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap, and no dice.

Searching around for these errors turns up a lot about CSS, which is exactly what I'm trying to avoid using (since I need to load fonts dynamically).

Please let me know how to go about this, either through local files or a proper download URL. I can download each file via Axios first, but would rather avoid it if possible.

Thanks so much!

0 Answers
Related