2017-04-17 140 views
1

我需要使用WebFontLoader在運行時按需加載字體(.ttf,.otf)。如何使用Google WebFontLoader通過URL加載自定義字體

每種字體都只有fontFamily和url。

看起來使用.css文件類似像WebFontLoader有一個選項來加載字體:

WebFont.load({ 
    custom: { 
     families: [ 
      'font-family-name' 
     ], 
     urls: [ 
      'path-to-css' 
     ] 
    } 
}); 

有沒有辦法做到這一點不.css文件,但與直接的路徑字體文件?

我不想使用任何外部網站來存儲我的字體文件。

回答

1

加載加載並檢測該字體已加載,我發現的唯一可能的方法是創建<style>元素與@font-face裏面並將其添加到DOM。

let markup = [ 
     '@font-face {\n', 
     '\tfont-family: \'', font-family-name, '\';\n', 
     '\tfont-style: \'normal\';\n', 
     '\tfont-weight: \'normal\';\n', 
     '\tsrc: url(\'', font-file-url, '\');\n', 
     '}\n' 
    ].join(''); 
}); 

let style = document.createElement('style'); 
style.setAttribute('type', 'text/css'); 
style.innerHTML = markup; 

,然後你可以使用WebFontLoader偵聽事件:

WebFont.load({ 
    custom: { 
     families: [ 
      'font-family-name' 
     ], 
     active:() => { 
      //triggers when font has been loaded successfully 
     }, 
     inactive:() => { 
      //triggers when font loading failed 
     } 
    } 
});