canvas离屏画布,两张图片合成并下载

 <view style="width: 100%; height: 750rpx; position: absolute; left: -9999px; top: -9999px;">
      <canvas type="2d" id="myCanvas" class="canvas"></canvas>
    </view>
 openDialog() {
    const that = this
    this.setData({
      show: true
    })
    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 dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr);
        // 加载大图
        const img1 = canvas.createImage()
        img1.src = '../../static/image/ShareQRCode.png'
        img1.onload = () => {
          ctx.drawImage(img1, 0, 0, res[0].width, res[0].height)
          // 加载小图
          const img2 = canvas.createImage()
          img2.src = '../../static/icon/headSculpture.png'
          img2.onload = () => {
            // 计算小图的位置和大小,使其铺满画布的一部分
            const imgWidth = (res[0].width / 2) - 30 // 小图宽度为画布宽度的一半
            const imgHeight = (res[0].height / 2) - 60 // 小图高度为画布高度的一半
            const imgX = (res[0].width - imgWidth) / 2 // 小图在水平方向居中
            const imgY = ((res[0].height - imgHeight) / 2) + Number(30) // 小图在垂直方向居中
            ctx.drawImage(img2, imgX, imgY, imgWidth, imgHeight) // 在计算出的位置绘制小图
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: canvas.width,
              height: canvas.height,
              destWidth: canvas.width,
              destHeight: canvas.height,
              canvas: canvas,
              success: function (res) {
                console.log('生成的临时图片路径:', res.tempFilePath) //生成的临时图片路径
                that.setData({
                  ShareQRCode: res.tempFilePath
                })
              },
              fail(err) {
                console.log('生成的临时图片路径失败:', err);
              }
            })
          }
        }
      })
  },

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

源码地址

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值