微信小程序 canvas绘制Base64数据图片

微信小程序canvas不支持直接绘制base64格式图片,按以下步骤可以绘制:
1、用wx.getFileSystemManager().writeFile方法,把base64格式图片转为binary格式图片,写入本地;
2、canvas绘制binary格式图片;
3、绘制完毕,用wx.getFileSystemManager().unlink方法,删除binary格式图片;

代码如下:

draw: function(obj) {
   let promise = new Promise((resolve, reject) => { 
      let filePath = `${wx.env.USER_DATA_PATH}/${obj.id}`; 
      wx.getFileSystemManager().writeFile({
        filePath: filePath,
        data: wx.base64ToArrayBuffer(this.getBase64Data(obj.url)),
        encoding: 'binary',
        success: () => { 
          console.log('写入成功, 路径: ', filePath);
          resolve(filePath); 
        },
        fail: err => {
          reject('写入失败:', err);
        },
      });
    })
    return new Promise((resolve, reject) => {
      promise.then(filePath => {
        var ctx = wx.createCanvasContext('canvas');
        ctx.drawImage(filePath, 0, 0, 300, 300);
        ctx.draw(false, () => {
          wx.canvasToTempFilePath({
            canvasId: 'canvas',
            success: res => {
              let saveFilePath = res.tempFilePath;
              /// 删除写入的数据
              wx.getFileSystemManager().unlink({
                filePath: filePath,
                success: res => {
                  console.log('删除成功, 路径: ', filePath);
                  resolve(saveFilePath);
                },
                fail: err => {
                  reject('删除失败:', err);
                }
              })
            },
            fail: err => {
              reject('保存图片到本地失败:', err);
            }
          })
        })
      }, err => {
        reject(err);
      })
   }) 
}

具体demo:https://developers.weixin.qq.com/s/mz2yComp7Id4

你可能感兴趣的:(微信小程序 canvas绘制Base64数据图片)