微信小程序canvas 生成二维码图片,画图片,生成图片,将两个canvas结合并保存图片

需求实现步骤如下

  1. 先定义两个canvas
  2. 一个canvas myQrcode画二维码的图片
  3. 另一个canvas mycanvas画一个背景图,并把二维码画到这个canvas上,mycanvas这个canvas生成一张图片,返回图片的临时路径
  4. 最后保存图片到手机

首先wxml,新版微信小程序canvas要注意写 type="2d" id="XXX"

html 复制代码
<canvas type="2d" style="width: 750rpx;height: 1260rpx;position:fixed;top: 1000px;left: 0px;z-index: 9999999999;" id="mycanvas"></canvas>
<canvas type="2d" style="width: 200rpx;height: 200rpx;position:fixed;top: 1000px;left: 0px;z-index: 9999999999;" id="myQrcode"></canvas>

画图

安装weapp-qrcode-canvas-2d

bash 复制代码
npm install weapp-qrcode-canvas-2d --save

weapp-qrcode-canvas-2d github

inviteBg是返回的微信临时图片地址

javascript 复制代码
import {
  loadImg
} from '../../utils/drawPoster'
Page({
	onLoad(){
    const ewmLink = getApp().api.requestBase + '/index?user_id=' + userInfo.userId;
    const img = 'https://jingdong-sauce.oss-cn-beijing.aliyuncs.com/images/b49632186701d80f507a0b0930a34435.jpg'

    loadImg('#mycanvas', '#myQrcode', ewmLink, img, this, (base64) => {
      console.log(base64)
      this.setData({
        inviteBg: base64,
        saveImgShow: true
      })
    })
	}
})

先通过wx.createSelectorQuery(),查询到两个canvas

然后画二维码图片drawCode,并生成二维码临时图片canvasToTempFilePath

canvas1.createImage() ctx.drawImage(img, 0, 0, canvas1.width / 3, canvas1.height / 3); 将背景图片画到canvas1上

canvas1.createImage() ctx.drawImage(img2, canvas1.width / 6 - 70, 340, 140, 140) 将二维码图片画到canvas1上

wx.canvasToTempFilePath 生成canvas1背景图和二维码图片结合的临时图片并返回

drawPoster.js

javascript 复制代码
import drawQrcode from 'weapp-qrcode-canvas-2d'
// 假设你已经引入了 qrcode.js
export function loadImg(canvasId1, canvasId2, ewmLink, imgUrl, context, callback) {
  const query = wx.createSelectorQuery()
  query.select(canvasId1).fields({
    node: true,
    size: true
  })
  query.select(canvasId2).fields({
    node: true,
    size: true
  })
  query.exec(async (res) => {
    console.log(res)
    const canvas1 = res[0].node
    const canvas2 = res[1].node
    // 调用方法drawQrcode生成二维码
    let img2Src = await drawCode(canvas2, canvasId2, ewmLink)
    console.log('img2Src', img2Src)
    const ctx = canvas1.getContext('2d')
    const dpr = wx.getSystemInfoSync().pixelRatio
    canvas1.width = res[0].width * dpr
    canvas1.height = res[0].height * dpr
    ctx.scale(dpr, dpr)
    const img = canvas1.createImage()
    img.src = imgUrl
    img.onload = () => {
      ctx.drawImage(img, 0, 0, canvas1.width / 3, canvas1.height / 3);
      console.log(ctx)
      const img2 = canvas1.createImage()
      img2.src = img2Src
      img2.onload = () => {
        ctx.drawImage(img2, canvas1.width / 6 - 70, 340, 140, 140)
        wx.canvasToTempFilePath({
          canvasId: canvasId1,
          canvas: canvas1,
          x: 0,
          y: 0,
          width: 414,
          height: 695,
          destWidth: 414,
          destHeight: 695,
          success(res) {
            console.log('合成图片路径', res.tempFilePath)
            callback(res.tempFilePath)
          },
          fail(res) {
            console.error(res)
          }
        })
      }
    }
  })

}

function drawCode(canvas, canvasId, ewmLink) {
  return new Promise(async (resolve, reject) => {
    await drawQrcode({
      canvas: canvas,
      canvasId: canvasId,
      width: 200,
      padding: 30,
      background: '#ffffff',
      foreground: '#000000',
      text: ewmLink,
    })
    wx.canvasToTempFilePath({
      canvasId: canvasId,
      canvas: canvas,
      x: 0,
      y: 0,
      width: 260,
      height: 260,
      destWidth: 260,
      destHeight: 260,
      success(res) {
        resolve(res.tempFilePath)
        console.log('二维码临时路径:', res.tempFilePath)
      },
      fail(res) {
        console.error(res)
      }
    })
  })

}

保存图片

点击保存图片,至此就能把这个图片保存到手机里啦

javascript 复制代码
    const query = wx.createSelectorQuery()
          query.select('#mycanvas').fields({
            node: true,
            size: true
          }).exec(res => {
            wx.canvasToTempFilePath({
              canvas: res[0].node,
              success: function (res) {
                console.log("uuuu22222")
                wx.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: function () {
                    console.log("33333")
                    wx.showToast({
                      title: '保存成功',
                    })

                  }
                })
              },
              fail: function (res) {
                console.log("444444")
                console.log(res);
              }
            }, _this);
          })
相关推荐
m0_587383004 小时前
广州 24 小时自助健身房解决方案技术实现与实战指南
java·spring·小程序·架构·需求分析
迪飞特科技8 小时前
智慧物业平台实战:Spring Boot 整合小程序实现报修巡检费用全流程
spring boot·后端·小程序
微笑的曙光11 小时前
第八期 · 情绪闯关挑战盒:一个「无惩罚」成就系统的数据建模
java·微信小程序
m0_5873830013 小时前
无人自助拼豆系统从需求分析到落地部署全流程实战开发指南
java·经验分享·后端·struts·小程序·架构·需求分析
小小王app小程序开发14 小时前
DIY水晶小程序玩法开发功能分析
小程序
andrsted15 小时前
练题簿在线免费刷题:顺序续练、优先新题与题型筛选,让复习一轮轮推进
微信小程序·小程序·刷题
拖孩16 小时前
全程 AI 写的小程序,刚接上会员虚拟支付,上线第二天就有人真金白银买单了|双签名、定价、iOS 的坑我全踩了一遍
前端·后端·微信小程序
2501_9159214316 小时前
详细教程:使用Perfdog工具测量iOS应用的功耗性能与优化方法
android·macos·ios·小程序·uni-app·cocoa·iphone
醒醒11116 小时前
深入浅出:如何用 Python 实现一个小程序污点分析引擎
微信小程序
andrsted18 小时前
练题簿在线免费刷题:Excel、CSV 批量导题与章节整理,把现成表格变成日常题库
学习·微信小程序·小程序·刷题·在线刷题