一、小程序Canvas画图示例:

drawCanvas: async function () {
    // 获取小程序码
    const code = await this.getCode()
    const scale = screenProportion()
    const size = setActualSize(526, 850)
    const rectSize = setActualSize(128, 128)
    const codeSize = setActualSize(110, 110)
    const disTop = 662 / scale
    const disLeft = 348 / scale
    const ctx = wx.createCanvasContext('shareCanvas')
    ctx.drawImage(this.data.templateBgImage, 0, 0, size.w, size.h)
    drawRoundRect(ctx, disLeft, disTop, rectSize.w, rectSize.h, 20 / scale, '#fff', '#D9D6FF')
    ctx.drawImage(code, disLeft + (9 / scale), disTop + (9 / scale), codeSize.w, codeSize.h)
    ctx.draw()
  },

//  canvas 绘制圆角矩形 ctx -- canvas实例
function drawRoundRect(ctx, x, y, width, height, radius, color, shadowColor) {
  ctx.save() // save方法,保存了当前设置
  ctx.beginPath()
  ctx.shadowColor = shadowColor;
  ctx.shadowOffsetX = 0;
  ctx.shadowOffsetY = 1;
  ctx.shadowBlur = 12;
  ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2)
  ctx.lineTo(width - radius + x, y)
  ctx.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2)
  ctx.lineTo(width + x, height + y - radius)
  ctx.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2)
  ctx.lineTo(radius + x, height + y)
  ctx.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI)
  ctx.fillStyle = color
  ctx.fill()
  ctx.closePath()
  ctx.restore() // restore方法,恢复了保存前的设置
}

// 不同屏幕下适配比例
function screenProportion() {
  let scale = 1;
  try {
    const res = wx.getSystemInfoSync();
    scale = 750 / res.windowWidth; // 不同屏幕下的适配比例
  } catch (e) {
    // Do something when catch error
    console.log("获取设备信息失败" + e);
  }
  return scale;
}


// 保存到相册
savePic() {
  wx.canvasToTempFilePath({
    canvasId: 'shareCanvas',
    success(res) {
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(res) {
          wx.showToast({
            title: '已保存到相册'
          })
        }
      })
    }
  })
}

二、图片处理:

① 保存网络图到本地;

function getImgLocalInfo (pSrc) {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: pSrc,
      success (res) {
        resolve(res)
      },
      fail (reason) {
        resolve(reason)
      }
    })
  })
}

② 保存远程图片流(base64)到本地;

//urlString 为图片的base64进制字符串
const urlString = urlString.replace('data:image/png;base64,', '') // 除去 ‘data:image/png;base64,’
const fs = wx.getFileSystemManager()
const fileName = wx.env.USER_DATA_PATH + '/' + name
fs.writeFileSync(fileName, urlString, 'base64')
return fileName

③保存convas图到本地

// 保存到相册
savePic() {
  wx.canvasToTempFilePath({
    canvasId: 'shareCanvas',
    success(res) {
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(res) {
          wx.showToast({
            title: '已保存到相册'
          })
        }
      })
    }
  })
}