Nico Müller
Nico Müller

Reputation: 1874

Dynamically load font from file based on userinput

I built a small styling simulator for an app of our company so that designers can quickly check color options/border styles etc for our app. I used mainly CSSvariables that change when adapting colors via a color picker / adapt values in a config JSON.

The designers should be able to also test different font styles in the JSON but I can't get it to work with local font files.

How can I achieve to load local fonts from a local folder too? I want to achieve this live so that the difference can be seen when entering a different font.

Just loading in example "Courier" works as its a system font but when I want to load it from a folder it doesn't work.

This is how I am loading the fonts into a CSS variable (the get value is just providing a safe method to access the JSON)

JS

$(":root")[0].style.setProperty("--regularFont", "/fonts/" + getValue(parsedConfig,['configs', 0, 'styleSheet', 'fonts', 'regularFont'],"") + ".tff");
      $(":root")[0].style.setProperty("--boldFont", "/fonts/" + getValue(parsedConfig,['configs', 0, 'styleSheet', 'fonts', 'boldFont'],"") + ".tff");

JSON:

"fonts": {
      "regularFont": "Arial",
      "boldFont": "AvenirNext-Bold"

CSS

@font-face {
  font-family: sans-serif; 
  font-family: regularFont;
  src: local(var(--regularFont)),
       url(var(--regularFont));
}

@font-face {
  font-family: sans-serif; 
  font-family: boldFont;
  src: local(var(--boldFont)),
       url(var(--boldFont));
       font-weight: bold;
}

/* example Styling */
.card {
    font-family: regularFont;
}

Upvotes: 4

Views: 2037

Answers (1)

D. Pardal
D. Pardal

Reputation: 6597

You can create a FontFace object with the data from the File object and the add it to the document's FontFaceSet:

const fontInput = document.getElementById("font-input"),
test = document.getElementById("test");

let font;

fontInput.addEventListener("input", async () => {
  if (font)
    document.fonts.remove(font);

  const data = await fontInput.files[0].arrayBuffer();
  font = new FontFace('test-font', data);
  await font.load();
  document.fonts.add(font);
  test.style.fontFamily = `test-font`;
});
<input type="file" id="font-input">
<p id="test">Upload a font to change me!</p>

Upvotes: 5

Related Questions