user798080
user798080

Reputation:

Font-Face changing via JavaScript

So the basic workflow is this:

  1. Asynchronous file upload of a font (this is already done).

  2. Get the URL (done).

  3. Change the font to the new URL.

I realize this needs to be done via font-face, but I can't seem to figure out how to access that via JavaScript.

Upvotes: 30

Views: 43334

Answers (4)

phnghue
phnghue

Reputation: 1686

Using js to create style element in document and then append TextNode child to it. Simple function:

function loadFont(name,url){
    var newStyle = document.createElement('style');
    newStyle.appendChild(document.createTextNode('@font-face{font-family: '+name+'; src: url('+url+');}'));
    document.body.appendChild(newStyle)
}

Example using:

loadFont("bonbon","fonts/bonbon.ttf");

Upvotes: 0

Cybernetic
Cybernetic

Reputation: 13334

Define a FontFace object:

new_font = new FontFace('conthrax', 'url(fonts/conthrax-sb.ttf)')

Call its load method to download the font:

new_font.load().then(function(loaded_face) {
    // use font here

}).catch(function(error) {

});

... this returns a Promise, which when resolved passes the loaded FontFace.

Add the loaded font to the document:

new_font.load().then(function(loaded_face) {
    // use font here
    document.fonts.add(loaded_face)
}).catch(function(error) {

});

Upvotes: 20

Paul Iştoan
Paul Iştoan

Reputation: 61

Try something like this:

let font = new FontFace("ExampleFont", 'url(ExampleFont.woff2) format("woff2")');
font.load().then(function(loadedFont)
{
    document.fonts.add(loadedFont);
    //do something after the font is loaded
}).catch(function(error) {
    // error occurred
});

Upvotes: 2

Ry-
Ry-

Reputation: 224859

You can create a new <style> element with the @font-face rule and append it to the document's head:

var newStyle = document.createElement('style');
newStyle.appendChild(document.createTextNode("\
@font-face {\
    font-family: " + yourFontName + ";\
    src: url('" + yourFontURL + "') format('yourFontFormat');\
}\
"));

document.head.appendChild(newStyle);

Of course, you'll probably need to provide all the necessary font formats and URLs, too, unless you're only worried about support for modern desktop browsers (in which case you would just use WOFF – I assume that's reasonable, because of the other features you mentioned).

Upvotes: 43

Related Questions