转换和渲染 web 字体到 base64-保持原始外观

我想推迟字体加载在我的网站启发 Smashing Magazine 的延迟字体加载逻辑

主要工作是将字体转换为 base64并准备 CSS 文件:

  1. 谷歌网页字体上选择字体并下载它们。
  2. 使用 字体松鼠 Webfont 生成器将下载的 TTF 文件转换为具有 base64嵌入式 WOFF 字体的 CSS 文件(专家选项-> CSS-> Base64 Encode)。
  3. 加载 CSS 文件异步(这里不重要)。

用于 Open Sans Bold 的 CSS 片段:

@font-face {
font-family: 'Open Sans';
src: url(data:application/x-font-woff;charset=utf-8;base64,<base64_encoded>) format('woff');
font-weight: 700;
font-style: normal;
}

转换了 字体看起来很不一样问题是。看看 Open Sans Bold: GWF vs base64 rendering comparison

特别是注意口音偏离和绝对可怕的字母 a。其他字体系列和变体看起来也有很明显的不同(大小和形状失真等)。


所以问题是: 如何正确地将来自 GoogleWebFonts (或其他来源)的 TTF 文件编码为 base64格式,并以与原始文件相同的方式使用它?

110982 次浏览

In the Font Squirrel Expert options, make sure to set the 'TrueType Hinting' option to 'Keep Existing'. Either of the other options will cause the TrueType instructions (hints) to be modified, which will in turn affect the rendering of the font.

Alternatively, if you're happy with the rendering of the font directly from GWF, you can just take that file and do the base64 encoding yourself. In OS X or Linux, use the built-in base64 command in Terminal/shell:

$ base64 myfont.ttf > fontbase64.txt

For Windows, you'll need to download a program to encode in base64 (there are several free/Open Source tools available). Copy the contents of that file, then use in your CSS as:

@font-face {
font-family: 'myfont';
src: url(data:font/truetype;charset=utf-8;base64,<<copied base64 string>>) format('truetype');
font-weight: normal;
font-style: normal;
}

(Note that you may need to make some adjustments to the various @font-face info to match your particular font data; this is just an example template)

Use this code snippet to base64 encode your font directly in the browser (OS independent, no need to install anything)

function base64convert (files) {
console.clear()
const reader = new FileReader()
reader.onload = (e) => {
console.log(e.target.result)
}
reader.readAsDataURL(files[0])
}
<input type="file" onchange="base64convert(this.files)">

Then copy the output and paste it into your CSS:

@font-face {
font-family: 'myfont';
src: url("<<copied base64 string>>");
}

A much simpler way to get the base64 code for Google Fonts is to use the following tool: https://amio.github.io/embedded-google-fonts/

input the URL to your font and you get the base64 code back straight away :)