直接上代碼
var self = this;
uni.loadFontFace({
family: 'Bitstream Vera Serif Bold',
source: 'url("https://sungd.github.io/Pacifico.ttf")',
success() {
console.log('success')
self.goto.fontFamily = 'Bitstream Vera Serif Bold'
}
})
uni.loadFontFace(Object object)
動(dòng)態(tài)加載網(wǎng)絡(luò)字體,文件地址需為下載類型。微信小程序 '2.10.0'起支持全局生效,需在 app.vue 中調(diào)用。
注意:
- 引入中文字體,體積過(guò)大時(shí)會(huì)發(fā)生錯(cuò)誤,建議抽離出部分中文,減少體積,或者用圖片替代
- 微信小程序端只支持網(wǎng)絡(luò)字體,字體鏈接必須是https。App支持網(wǎng)絡(luò)或本地的字體(本地字體需使用平臺(tái)絕對(duì)路徑)。
- 微信小程序端字體鏈接必須是同源下的,或開啟了cors支持,微信小程序的域名是servicewechat.com
- canvas等原生組件不支持使用接口添加的字體
- 工具里提示 Faild to load font可以忽略
平臺(tái)差異說(shuō)明
| 5+App | H5 | 微信小程序 | 支付寶小程序 | 百度小程序 | 字節(jié)跳動(dòng)小程序 | QQ小程序 |
|---|---|---|---|---|---|---|
| 1.9.0+ 自定義組件編譯模式 | 2.3.4+ | 基礎(chǔ)庫(kù) 2.1.0+ | 1.11.0+ | x | x | x |
參數(shù)說(shuō)明
| 屬性 | 類型 | 默認(rèn)值 | 必填 | 說(shuō)明 |
|---|---|---|---|---|
| family | String | 是 | 定義的字體名稱 | |
| source | String | 是 | 字體資源的地址。建議格式為 TTF 和 WOFF,WOFF2 在低版本的iOS上會(huì)不兼容。 | |
| desc | Object | 否 | 可選的字體描述符 | |
| success | Function | 否 | 接口調(diào)用成功的回調(diào)函數(shù) | |
| fail | Function | 否 | 接口調(diào)用失敗的回調(diào)函數(shù) | |
| complete | Function | 否 | 接口調(diào)用結(jié)束的回調(diào)函數(shù)(調(diào)用成功、失敗都會(huì)執(zhí)行) |
Object.desc 的結(jié)構(gòu)
| 屬性 | 類型 | 默認(rèn)值 | 必填 | 說(shuō)明 |
|---|---|---|---|---|
| style | String | normal | 否 | 字體樣式,可選值為 normal / italic / oblique |
| weight | String | normal | 否 | 字體粗細(xì),可選值為 normal / bold / 100 / 200../ 900 |
| variant | String | normal | 否 | 設(shè)置小型大寫字母的字體顯示文本,可選值為 normal / small-caps / inherit |
代碼示例
uni.loadFontFace({
family: 'Bitstream Vera Serif Bold',
source: 'url("https://sungd.github.io/Pacifico.ttf")',
success() {
console.log('success')
}
})