1. 页面绑定canvas
<view style='width:0px;height:0px;overflow:hidden;'>
<!-- 
//调试时候可用直接将canvas显示在页面上
//调试完成将canvas隐藏
<canvas  id="canvasContaner" type="2d" ></canvas>-->
<canvas  id="canvasContaner" type="2d"  style="position:fixed;left:9999px" ></canvas> 
</view>
  1. onReady时获取canvas对象并设置画布尺寸
onReady() {
    const query = wx.createSelectorQuery()
    query.select('#canvasContaner')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        // console.log(res)
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        this.setData({
          canvas,
          ctx
        })
        const dpr = wx.getSystemInfoSync().pixelRatio;
        // console.log(wx.getSystemInfoSync())
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        canvas.width = 1024 * dpr;
        canvas.height = 968 * dpr;
        ctx.scale(dpr, dpr)

        ctx.fillStyle = "#FFF";
        ctx.fillRect(0, 0, 1024, 968)
      })
  }
  1. 部分绘图函数
//绘制图片
//image可用传递代码中的图片文件(注意路径需要是相对路径)
//也可以直接传递base64字符串
//本地路径也支持(例如下载网络图片到本地随后再进行绘制的本地路径)
//需要注意如果是本地路径需要添加微信的路径(wx.env.USER_DATA_PATH)  例如: let filePath = wx.env.USER_DATA_PATH + "/" + fileName;
async drawImg(img, x, y, width, height) {
    return new Promise((resolve, reject) => {
      try {
        const image = this.data.canvas.createImage()
        image.onload = () => {
          this.data.ctx.drawImage(
            image,
            x,
            y,
            width,
            height,
          )
          resolve(img)
        }
        image.src = img;
      } catch (error) {
        console.log(error)
        reject(error)
      }
    });

  }
  1. 文字
drawText(txt, x, y, font) {
    //魔法绘画-让小朋友线稿变电影大片
    this.data.ctx.font = font;
    this.data.ctx.fillText(txt, x, y);
  }

//字体指定时需要注意格式
调用方式  this.drawText("test", 512 - 150, 768 - 35, "20px sans-serif");
  1. 填充背景
this.data.ctx.fillStyle = "#FFF";
this.data.ctx.fillRect(0, 0, 1024, 968)
  1. 保存canvas结果到图片中
wx.showLoading();
wx.canvasToTempFilePath({
      canvas: this.data.canvas,
      success(res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            // console.log(res)
            wx.hideLoading()

            wx.showToast({
              title: '保存成功',
              icon: "success"
            })
          },
          fail: function (err) {
            // console.log(err)
            wx.hideLoading()

            wx.showToast({
              title: err,
              icon: "none"
            })
          }
        })
      }
    })

留待后查,同时方便他人