微信小程序canvas画布绘制base64图片并保存图片到相册中

WXML部分:(尽量用px,不用百分比)

<view class="img_" style="width: 400px;">
  <canvas type="2d" id="canvasId" style="width: 400px;height: 500px"></canvas>
  <button style="margin: auto;width: 70%;margin-top: 10px;" bindtap="saves">保存图片</button>
</view>

样式可以根据自己的需要去调整

canvas 绘制成图片部分:

//写在接口成功回调中
        const fs = wx.getFileSystemManager();
        var codeimg = wx.env.USER_DATA_PATH + '/' + '.jpg';
        fs.writeFile({
          filePath: codeimg,
          data: res.data.slice(22), // code就是接口返回的base64数据(分割掉前面的data:image/png;base64,)
          encoding: 'base64',
          success: () => {
            // console.log(codeimg);

            wx.createSelectorQuery().select('#canvasId').fields({
              node: true,
              size: true
            })
              .exec((res) => {
                console.log(res);
                let ctx = res[0].node.getContext('2d'); //getContext返回Canvas 的绘图上下文              
                let canvas = res[0].node;
                const bg = canvas.createImage();
                const image = canvas.createImage();
                const dpr = wx.getSystemInfoSync().pixelRatio;
                let {width,height} = res[0].node
                res[0].node.width = width * dpr;
                res[0].node.height = height * dpr;
                console.log(width,dpr);
                // 设置图片src
                image.src = 'https://pic.imgdb.cn/item/647d31011ddac507cc160e75.jpg'
                bg.src = codeimg;
                image.onload = function () {
                  ctx.drawImage(image, 0, 0, width * dpr, height * dpr);
                  ctx.drawImage(bg, 240, 210, 430, 160);
                  // ctx.draw();
                }
                // ctx.draw()
                console.log(ctx);
                that.setData({
                  ctx:canvas
                 })
              })
          },
        })

图片保存功能:

首先获取用户相册权限。

// 检查用户是否已经授权
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          // 如果用户未授权,则向用户请求授权
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              console.log('授权成功')
            },
            fail: () => {
              console.log('授权失败')
            }
          })
        } else {
          console.log('已经授权')
        }
      }
    })

保存到相册:

// 保存图片
  saves() {
      let _this = this;
      wx.canvasToTempFilePath({
        // 把画布转化成临时文件
        x: 0,
        y: 0,
        width: 380, // 截取的画布的宽
        height: 600, // 截取的画布的高
        destWidth: 380, // 保存成的画布宽度
        destHeight: 600, // 保存成的画布高度
        fileType: 'jpg', // 保存成的文件类型
        quality: 1, // 图片质量
        //如果图片不是2D的话,就需要使用canvasId属性,详情请查看微信小程序官方文档
        canvas:_this.data.ctx, // 画布实例
        success(res) {         
          // 2-保存图片至相册
          wx.saveImageToPhotosAlbum({
            // 存成图片至手机
            filePath: res.tempFilePath,
            success(res2) {
              wx.hideLoading();
              wx.showToast({
                title: '保存成功',
                duration: 2000
              });
            },
            fail(res3) {
              if (res3.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
                wx.showToast({
                  title: '保存失败,稍后再试',
                  duration: 2000,
                  icon: 'none'
                });
                wx.hideLoading();
              } else {
                wx.showToast({
                  title: '保存失败,稍后再试',
                  duration: 2000,
                  icon: 'none'
                });
                wx.hideLoading();
              }
            }
          });
        },
        fail(err) {
          console.log(err);
          
          wx.showToast({
            title: '保存失败,稍后再试',
            duration: 2000,
            icon: 'none'
          });
          wx.hideLoading();
        }
      });
    }

猜你喜欢

转载自blog.csdn.net/m0_74801194/article/details/132520163