准备工作,获取字体链接
还原设计稿的时候需要用到如下特殊字体(google 的 Montserrat):
https://fonts.google.com/specimen/Montserrat
- 选择这个字体
- 下载全部字体
-
将本地的字体文件上传到自己的cdn,(google的源在国内不友好)
文件解压后如下:
选择需要的字体文件上传到cdn上,获得如下链接
https://images.pandaomeng.com/Montserrat-Regular.ttf
https://images.pandaomeng.com/Montserrat-Medium.ttf
在小程序中使用
-
官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/media/font/wx.loadFontFace.html
-
封装一个载入字体的util,代码如下
utils/loadFont.js
-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
let loadFont = function (weight = 400) { const source = { 400: 'url("https://images.pandaomeng.com/Montserrat-Regular.ttf")', // Regular 500: 'url("https://images.pandaomeng.com/Montserrat-Medium.ttf")' // Medium } wx.loadFontFace({ family: 'Montserrat', source: source[weight], desc: { weight: weight }, success: function(message) { console.log('load font-family success:', message) }, fail: function (message) { console.log('load font-family fail: ', message) } }) }
export default loadFont
|
-
在需要用到的地方引入
pages/xxx/xxx.js
1 2 3 4 5
|
import loadFont from '../../utils/loadFont'
onLoad () { loadFont(400) }
|
pages/xxx/xxx.wxss
1 2 3 4 5
|
.test { font-size: 38rpx; font-weight: 400; font-family: 'Montserrat'; }
|