如何製作「字體預覽」的網頁功能

為什麼要學這個?

  • 使用者在還沒有下載該字體,就可以直接線上在網頁裡輸入他想看的文字套用新字體後的效果。
  • 行動裝置變多,如果想讓你的網頁裡的文字,看起來不是標準的字體,應該要學。

實作步驟

1:把字體先轉換成 .woff 格式,幸運的話,字體檔案大小會縮小到6成左右。

2:把檔案放到網路上可以被公開存取的空間。
(例如自行架設的網站或放在github上)

3:在自己的網頁裡,符用這段 HTML:

<style>
@font-face {
font-family: SweiB2LegCJKtc-Regular;
src: url(https://github.com/max32002/swei-b2-leg/raw/master/WebFont/CJK%20TC/SweiB2LegCJKtc-Regular.woff2) format(“woff2”), url(https://github.com/max32002/swei-b2-leg/raw/master/WebFont/CJK%20TC/SweiB2LegCJKtc-Regular.woff) format(“woff”);
}
.sweib2leg_textarea {
display: block;
width: calc(100% – 46px);
height: 96px;
margin: 10px;
padding: 12px;
background: #fff;
border:1px solid #333;
border-radius: 2px;
box-shadow: inset 3px 3px 3px rgba(0,0,0,0.25);
-moz-box-shadow: inset 3px 3px 3px rgba(0,0,0,0.25);
-webkit-box-shadow: inset 3px 3px 3px rgba(0,0,0,0.25);
font-size: 42px;
overflow: auto;
resize: none;
outline: none;
}
</style>
<script>
function sweib2leg_size_input_change(cnt){
var size_val = Number(document.getElementById(“sweib2leg_size_input_” + cnt).value);
document.getElementById(“sweib2leg_textarea_” + cnt).style.fontSize = size_val + “px”;
}
</script>

<p>測試效果:字體大小<input type=”number” id=”sweib2leg_size_input_0″ value=”42″ style=”width: 80px; text-align: right;” onchange=”sweib2leg_size_input_change(0);” onkeyup=”sweib2leg_size_input_change(0);”>px</p>

<textarea class=”sweib2leg_textarea” id=”sweib2leg_textarea_0″ style=”font-family: ‘SweiB2LegCJKtc-Regular'”>可以輸入文字測試效果</textarea>

附註:上面在github 上 webfont resource url 無法直接使用,會有CORS(Cross-Origin Resource Sharing)問題,解法參考:
https://stackoverflow.max-everyday.com/2020/08/cors/


執行畫面:

展示成品用網址:
https://max-everyday.com/2020/07/swei-b2-leg/

測試你的webfont 是否能被載入的線上服務:
Did that font really get loaded?
http://www.atomicjetpacks.com/project/fontdetect/how-to-detect-if-a-font-really-loaded


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”);
}


MaxCodeReview 影片:
https://youtu.be/-LfZ2ka6IYI


相關網頁:

發佈留言

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