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

WXML部分:
html 复制代码
    <view class="img_"  style="width: 100%;">
      <canvas type="2d" id="canvasId" style="width: 100%;height: 100%" ></canvas>      
      <button style="margin: auto;width: 70%;margin-top: 10px;" bindtap="saves">保存图片</button>
    </view>

样式可以根据自己需求自行调整

canvas绘制成图片部分:
javascript 复制代码
  //写在接口成功回调中
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;
                  res[0].node.width = res[0].node.width * dpr;
                  res[0].node.height = res[0].node.height * dpr;
                  // 设置背景图片src
                  image.src = 'https://pic.imgdb.cn/item/647d31011ddac507cc160e75.jpg'
                  bg.src = codeimg;
                  image.onload = function () {
                    ctx.drawImage(image, 0, 0, 900, 440)
                    ctx.drawImage(bg, 240, 210, 430, 160);
                
                  }
                // 将图片保存需要的实例,不写保存可以删除
                  that.setData({
                    ctx:canvas
                   })
                })
这就将图片绘制出来了。

图片保存功能:

首先获取用户相册权限。
javascript 复制代码
// 检查用户是否已经授权
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          // 如果用户未授权,则向用户请求授权
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              console.log('授权成功')
            },
            fail: () => {
              console.log('授权失败')
            }
          })
        } else {
          console.log('已经授权')
        }
      }
    })
保存功能:
javascript 复制代码
// 保存图片
  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();
        }
      });
    }
相关推荐
00后程序员张26 分钟前
iOS 26 内存占用监控 多工具协同下的性能稳定性分析实战
android·macos·ios·小程序·uni-app·cocoa·iphone
2501_915909062 小时前
iOS 26 性能监控工具有哪些?多工具协同打造全方位性能分析体系
android·macos·ios·小程序·uni-app·cocoa·iphone
simon_93493 小时前
微信小程序(H5)上传文件到阿里云 OSS(使用 STS 临时凭证)
阿里云·微信小程序·小程序·html5
2501_915918414 小时前
uni-app 上架 iOS 应用全流程 从云打包到开心上架(Appuploader)免 Mac 上传发布指南
android·macos·ios·小程序·uni-app·iphone·webview
老师可可5 小时前
成绩查询系统如何制作?
经验分享·学习·小程序·excel·学习方法
2501_915921435 小时前
iOS 抓包工具有哪些,开发者的选型与实战指南
android·ios·小程序·https·uni-app·iphone·webview
2501_915918415 小时前
iOS 26 应用管理实战 多工具协同构建开发与调试的高效体系
macos·ios·小程序·uni-app·objective-c·cocoa·iphone
游戏开发爱好者87 小时前
iOS 抓包工具实战 开发者的工具矩阵与真机排查流程
android·ios·小程序·https·uni-app·iphone·webview
TiAmo zhang12 小时前
微信小程序开发案例 | 通讯录小程序(下)
小程序·notepad++
汤姆丁111115 小时前
直播互动小程序端&Web运营端接入指南
小程序