[WeChat Mini Program] Three ways to use custom fonts

1. loadFontFace interface

The official interface provided by the applet is the most convenient way to load fonts, but there are many restrictions. It must be https and of the same origin, and native components such as canvas do not support it. Notice! ! Using a local file is not valid, a network address must be used.

Official document: wx.loadFontFace(Object object) | WeChat Open Documentation

Demo code:

wx.loadFontFace({
  family: 'DFPWaWa-B5',
  source: 'url("https://we7.stuyun.com/DFPWaWa-B5.ttf")',
  success: res => {
    console.log('font load success', res)
  },
  fail: err => {
    console.log('font load fail', err)
  }
})

2. face-font url

Traditional css rules, same as loadFontFace restrictions, must be https and of the same origin, do not support native components such as canvas, and do not support local files.

Demo code:

@font-face {
    font-family: 'DFPWaWa-B5';
    src: url("https://we7.stuyun.com/DFPWaWa-B5.ttf")
}

3. face-font base64

The method often introduced in online tutorials is to upload files to transfonter , and only check ttf for formats. You can convert the font into base64 face-font, copy it into wxss and use it. But the shortcomings are also obvious. The maximum size limit of a small program can only be 2m, and any Chinese font will exceed it.

1. Find fonts that require .ttf file for design

2. Convert the file through an online text conversion tool , and convert the font into a base64 face-font

Steps:

1. Click to open the online text conversion tool

2. Click the button Add fonts (add fonts, the file to be uploaded here is to find the .tff file for the design)

3. Turn on the Base64 encode button (Base64 encoding), the Formats button (format button) below just check the TTF format

4. Click the Convert button (conversion button), after conversion, click Download on the left to open the downloaded file, and there will be a stylesheet.css file inside

 

3. Copy the content of the downloaded stylesheet.css file and paste it into the wxss file to be used

  @font-face {
      font-family: 'DFPWaWa-B5';
      src: url('./fonts/DFPWaWa-B5.ttf') format('truetye');   //这里的路径为上面转换吼的base64的路径
    }

    .box {
      font-family: 'DFPWaWa-B5';      //运用在你所需要的标签样式上,名字和上面引入的font-family名称要一一对应,记得要加''
    }

4. Summary: It is best to use the loadFontFace interface officially provided by the mini program. The most convenient method of loading fonts has many limitations. My needs can only be achieved through the third method. It depends on your needs which method to use.

Guess you like

Origin blog.csdn.net/m0_71735156/article/details/132182224