微信小程序生成海报 / 两张图片合并生成一张

一张背景图,一个二维码,生成一张全屏海报,二维码位于右下角(二维码位置可以调整)

方法思路:使用微信小程序的canvas组件

1、获取canvas组件定义一个canvas上下文
2、获取设备信息,将设备宽高设置为canvas画布的大小
3、在图片加载完成后开始绘制,可以调整绘制图片的起始位置坐标以及大小
4、绘制完成后将canvas转成图片
5、下载到图库
javascript 复制代码
<canvas type="2d" id="myCanvas"></canvas>
javascript 复制代码
handleImg() {
    try {
      const query = wx.createSelectorQuery();
      query.select('#myCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        const systemInfo = wx.getSystemInfoSync();
        const dpr = systemInfo.pixelRatio;
        const { windowWidth, windowHeight } = systemInfo
        // 根据设备的像素比 把画布设为全屏
        canvas.width = windowWidth * dpr;
        canvas.height = windowHeight * dpr;
        ctx.scale(dpr, dpr)
        let that = this
        const img = canvas.createImage();
        img.src = '第一张图片的url';
        img.onload = () => {
          const qrcodeImg = canvas.createImage();
          qrcodeImg.src = '第二张图片的url'
          qrcodeImg.onload = () => {
          	// 绘制第一张图片
            ctx.drawImage(img, 0, 0, windowWidth, windowHeight);
            // 绘制第二张图片
            ctx.drawImage(qrcodeImg, windowWidth - 100, windowHeight - 100, 60, 60);
            // 延时保存图片
            setTimeout(() => {
              wx.canvasToTempFilePath({
                canvas,
                destWidth: windowWidth * dpr,
                destHeight: windowHeight * dpr,
                success(res) {
                  console.log('生成的图片路径:', res.tempFilePath);
                  that.saveImageToAlbum(res.tempFilePath)
                },
                fail(err) {
                  console.error('canvasToTempFilePath 保存失败:', err);
              });
            }, 500);
          }
        };
      });
    } catch (err) {
      console.log('trycatch失败',err)
    }
  },
  saveImageToAlbum(filePath) {
    wx.saveImageToPhotosAlbum({
      filePath: filePath,
      success(res) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        });
      },
      fail(err) {
        console.error('保存失败:', err);
      }
    });
  },

注意:

  • 等图片加载完成后开始绘制
  • 绘制完成后稍加延迟再转成图片

把图片链接准备好替换代码中的占位文字即可运行

有问题欢迎留言交流~

相关推荐
说私域3 小时前
开源链动2+1模式商城小程序在深度分销数字化转型中的应用研究
人工智能·小程序·开源·流量运营·私域运营
咖啡の猫4 小时前
微信小程序案例 - 自定义 tabBar
微信小程序·小程序·notepad++
咖啡の猫5 小时前
微信小程序全局数据共享
微信小程序·小程序
桐溪漂流5 小时前
微信小程序cli脚本预览上传
微信小程序·小程序
咖啡の猫5 小时前
微信小程序使用 npm 包
微信小程序·小程序·npm
说私域5 小时前
开源链动2+1模式商城小程序的营销技术与私域运营策略研究
人工智能·小程序·开源·流量运营·私域运营
小小王app小程序开发20 小时前
淘宝扭蛋机小程序核心玩法拆解与技术运营分析
大数据·小程序
说私域1 天前
AI智能名片商城小程序数据清洗的持续运营策略与实践研究
大数据·人工智能·小程序·流量运营·私域运营
东东5161 天前
xxx食堂移动预约点餐系统 (springboot+微信小程序)
spring boot·微信小程序·小程序·毕业设计·个人开发·毕设
CHU7290351 天前
一番赏盲盒抽卡机小程序:解锁惊喜体验与社交乐趣的多元功能设计
前端·小程序·php