微信小程序Canvas绘制使用iconfont

495 阅读1分钟

1.iconfont 操作

首先,在iconfont收集好自己需要的图标

然后在iconfont项目中点击生成代码,如下图所示:

20240123100201.png

然后复制ttf文件链接:

20240123100202.png

2.在微信小程序中使用

使用 loadFontFace 动态加载字体。

我们可以 app.js 中全局引入,或者在使用的地方引入。我们使用全局引入:

App({
  onLaunchfunction (e) {
    wx.loadFontFace({
      global: true, // 是否全局生效
      family: 'Iconfont', // 定义的字体名称
      source: 'url("https://at.alicdn.com/t/c/font_4400828_guvq22f95x9.ttf")', // 字体资源的地址
      scopes: ['webview', 'native'], // 字体作用范围,设置 native 可在 Canvas 2D 下使用
      success: (res) => {
        console.log(res)
      }
    })
  },
})

在绘制时使用:

canvasDraw () {
  const ctx = wx.createCanvasContext('canvasId')

  // fontFamily 使用我们上面定于的 Iconfont
  ctx.font = 'normal 44px Iconfont'
  // 设置字体颜色
  ctx.setFillStyle(#000)
  // 使用 iconfont 图标
  ctx.fillText('', 44, 44)
}

在绘制 iconfont 图标时,填充的文本在 iconfont 项目中。

点击编辑图标,复制字符:

20240123100203.png