套用和轉換字型為WebFont

Posted in :

很多漂亮的網站都有使用web font,效果比使用圖片來做好看而且方便維護,要套用web font 很簡單,在網頁裡加入幾行去引用網路上的 .woff2 到網頁裡,即可直接指定想要的文字套用引用的字型。

要轉換自己的 otf/ttf 字型為 web font 也很簡單,透過 fontforge 或其他線上的服務即可完成,如果有多次轉換的需求,使用 fontforge 會方便些。


WebFont 常見有2個格式.woff 和 .woff2。

WOFF is basically OTF or TTF with metadata and compression supported by all major browsers.

WOFF2 is the next generation of WOFF. The WOFF2 format offers a 30% average compression gain over the original WOFF. Because it still just a recommended upgrade, it does not have the wide support of WOFF.

反正現在網路速度都很快,建議先使用 .woff 隔幾年後大家的瀏覽器都升級了,再使用 .woff2。也有人建議可直接產 woff2 (壓縮率更佳),因目前主流瀏覽器皆已支援:
https://caniuse.com/#search=woff2


FontForge script to convert .ttf file to its webfont variations

FontForge 腳本:

#!/usr/local/bin/fontforge
Open($1)
Generate($1 + ".otf")
Generate($1 + ".svg")
Generate($1 + ".woff")
Generate($1 + ".woff2")

上面這個寫法真的滿精簡的,也可以參考看看Max的用法,轉成字體檔 (all font format to .ttf/.otf/.svg/.woff/.woff2)下載:
https://github.com/max32002/MaxFontScripts/blob/master/generate.py

Max 使用 FontForge 把 Swei-Gothic (獅尾圓體) ,原本15MB 的字型,轉成.woff2 只剩 5.6MB!好心動哦。


CSS 網頁字型

@font-face 這個 CSS 的 at-rule 可以讓網頁設計者可以使用網路上的字型檔來顯示網頁中的文字,@font-face 的基本使用方式:

@font-face {
font-family: YourFontName;
src: url(http://your-font-url/font-name.woff) format("woff");
}

有了上面的 style 後,就可以使用 font-family 屬性來指派我的網頁元件套用網路字型。

Css 寫法範例2號:

@font-face {
    font-family: "MyWebFont";
    src: url("webfont.woff2") format("woff2"), /* Super Modern Browsers */
    url("webfont.woff") format("woff"), /* Pretty Modern Browsers */
    url("webfont.ttf")  format("truetype") /* Safari, Android, iOS */
    font-weight: normal;
    font-style: normal;
}

Later on in the stylesheet:

body {
    font-family: "MyWebFont";
}

當 woff2 上 Github 後,可透過以下方式從 CDN 中引入,
可大幅加快網頁載入。jsDelivr 在速度上挺不錯的: www.cdnperf.com/#!performance,Asia 。

@font-face{
 font-family: naikai;
 src: url( https://cdn.jsdelivr.net/gh/max32002/naikaifont@770d2de358eb3eab35b4918a910cb6b06ff8e15a/webfont/NaikaiFont-Regular.woff2
) format(“woff2”);
}


相關文章:

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *