开发微信小游戏的时候,经常会用自定义的字体,而字体库也比较大,如果放在包体里,会占用仅有的20M包体,总启动时间也会变慢。通过外部加载的方式是首先想到的思路。我们用的是LAYA引擎,引擎原生的字体加载在微信中不生效,还是自己动手,丰衣足食。
总体思路是通过微信的下载方法,把字体库下载下来,再通过 wx.loadFont 来加载字体。为了效果更好,可以首次下载的时候把文件存起来,下次就可以直接用了。
function loadFont() {
const fs = wx.getFileSystemManager();
fs.getFileInfo({
filePath: `${wx.env.USER_DATA_PATH}/fzlb.ttf`,
success(res) {
readFont();
},
fail(res) {
wx.downloadFile({
url: 'https://xxx/fzlb.ttf',
success (res) {
if (res.statusCode === 200) {
console.log("font tempFilePath", res.tempFilePath);
const fs = wx.getFileSystemManager()
fs.copyFile({
srcPath: res.tempFilePath,
destPath: `${wx.env.USER_DATA_PATH}/fzlb.ttf`,
success(res) {
console.log("copysuc", res);
readFont();
},
fail(res) {
console.error("copyfail", res);
}
})
}
}
})
}
});
}
function readFont() {
var font = wx.loadFont(`${wx.env.USER_DATA_PATH}/fzlb.ttf`);
console.log('font >> '+ font);
defaultfont = font;
doBegin();
}