font.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // 建议循环调用方法,而不是这个方法内循环下载
  2. // 下载字体文件,注意要把字体域名加到后台downloadFile白名单中
  3. function _downloadFont(fontUrl, filePath, fontFamily) {
  4. wx.downloadFile({
  5. url: fontUrl,
  6. success: res => {
  7. wx.getFileSystemManager().saveFile({ // 下载成功后保存到本地
  8. tempFilePath: res.tempFilePath,
  9. filePath,
  10. success: res => {
  11. // 加载字体
  12. _loadFontFace(fontFamily, res.savedFilePath)
  13. }
  14. })
  15. }
  16. })
  17. }
  18. // 加载文件字体转 base64,load
  19. function _loadFontFace(fontFamily, filePath) {
  20. // 读文件
  21. wx.getFileSystemManager().readFile({
  22. filePath, // 本地文件地址
  23. encoding: 'base64',
  24. success: res => {
  25. wx.loadFontFace({
  26. global: true, // 是否全局生效
  27. scopes: ['webview'], //native可能有点问题,超哥生个海报试一下
  28. family: fontFamily, // 字体名称
  29. source: `url("data:font/woff2;charset=utf-8;base64,${res.data}")`,
  30. success(res) {
  31. console.log(fontFamily + '加载成功:' + res.status)
  32. },
  33. fail: function (res) {
  34. console.log(fontFamily + '加载失败' + res)
  35. },
  36. })
  37. }
  38. })
  39. }
  40. // fontUrl: 字体地址
  41. // filename: 存储文件路径
  42. // fontFamily: css 中字体的 family
  43. function loadCloudFontFace(fontUrl, filename, fontFamily) {
  44. const filePath = `${wx.env.USER_DATA_PATH}/${filename}`
  45. wx.getFileSystemManager().access({
  46. path: filePath,
  47. success: () => {
  48. _loadFontFace(fontFamily, filePath)
  49. console.log('从本地加载了字体');
  50. },
  51. fail: () => {
  52. _downloadFont(fontUrl, filePath, fontFamily)
  53. console.log('从外部加载了字体', fontUrl);
  54. }
  55. })
  56. }
  57. module.exports = {
  58. loadCloudFontFace
  59. }