微信小程序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);
          })
相关推荐
2501_933907214 小时前
深圳本凡科技专业企业APP开发,助力手机应用创新优化
科技·微信小程序·小程序
每天都要加油呀!6 小时前
TypeError: uni.requestPayment is not a function
小程序
java1234_小锋6 小时前
分享一套优质的微信小程序校园志愿者系统(SpringBoot后端+Vue3管理端)
微信小程序·小程序·校园志愿者
2501_916008898 小时前
深入解析iOS机审4.3原理与混淆实战方法
android·java·开发语言·ios·小程序·uni-app·iphone
打破砂锅问到底0078 小时前
AI 驱动开发实战:10分钟从零构建「微信群相册」小程序
人工智能·微信·小程序·ai编程
CHU7290358 小时前
扭蛋机盲盒小程序前端功能设计解析:打造趣味与惊喜并存的消费体验
前端·小程序
QT.qtqtqtqtqt9 小时前
uni-app小程序前端开发笔记(更新中)
前端·笔记·小程序·uni-app
CHU72903510 小时前
直播商城APP前端功能全景解析:打造沉浸式互动购物新体验
java·前端·小程序
黑客老李20 小时前
web渗透实战 | js.map文件泄露导致的通杀漏洞
安全·web安全·小程序·黑客入门·渗透测试实战
游戏开发爱好者81 天前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview