第一种 网络字体地址
const url = 'https://sungd.github.io/Pacifico.ttf'
loadFontWeb() {
uni.loadFontFace({
family: 'font-test',
source: `url("${url}")`
})
},
第二种 本地字体地址
第一步 在字体文件存放在static目录下面
第二步 本地路径需要使用绝对路径,所以需要native的方法来
loadFontLocal() {
uni.loadFontFace({
family: 'font-name', // 这里是字体的名字
// 本地字体路径需转换为平台绝对路径
source: `url(${plus.io.convertLocalFileSystemURL('_www/static/字体文件名.ttf')})`,
success() {
console.log('success')
},
fail(e) {
console.log('fail')
}
})
},
第三部 在CSS中对需要引用的字体 使用 font-family: 第二步填写的地址;
*{
font-family: '第二步的字体名字' !important;
}
第三种 网络地址缓存到本地
async loadFontCache() {
let tempFilePath,fontName = '自定义的字体名字'
const savedFilePath = uni.getStorageSync(fontName)
const [error, res] = await uni.getSavedFileList()
if (!error) {
const fileList = res.fileList
const file = fileList.find(file => file.filePath === savedFilePath)
if (file) {
tempFilePath = file.filePath
}
}
if (!tempFilePath) {
const [error, res] = await uni.downloadFile({
url,
})
if (!error) {
tempFilePath = res.tempFilePath
uni.saveFile({
tempFilePath,
success(res) {
uni.setStorage({
key: fontName ,
data: res.savedFilePath
})
}
})
} else {
console.log('下载失败')
return
}
} else {
console.log('使用缓存资源,跳过下载步骤')
}
uni.loadFontFace({
family: 'font-test',
source: `url("${plus.io.convertLocalFileSystemURL(tempFilePath)}")`
})
}
还有有个坑,不知道别人是不是跟我一样,就是在每个页面要引入字体 都需要调用一下 才会生效,所以我这里是写在main.js里面, 使用mixin,方法
Vue.mixin({
data(){
return {
query : '',
}
},
onLoad({query}) {
// #ifdef APP-NVUE || APP-PLUS || APP-PLUS-NVUE || APP-VUE
this.loadFontFaceFromLocal();
// #endif
},
methods:{
loadFontFaceFromLocal() {
uni.loadFontFace({
family: 'youmincho',
// 本地字体路径需转换为平台绝对路径
source: `url(${plus.io.convertLocalFileSystemURL('_www/static/youmingcho.ttf')})`,
success() {
console.log('success');
},
fail(e) {
console.log('fail');
}
});
}
}
})