微信小程序 canvas生成海报

本文介绍了如何使用微信小程序的canvas API,结合前端绘画技巧,捕获页面内容并将其转换为图片保存到本地或相册。涉及操作包括文字绘制、换行、矩形绘制、图片加载和用户头像绘制,最终通过`canvasToTempFilePath`实现图片导出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近遇到个需求,需要根据一个指定的页面,生成图片并且进行保存,大致就是需要在canvas上画出来和当前页面一样内容,然后转存为图片这样。
准备工作 先获取到canvas对象

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 = 640 * dpr
  canvas.height = 865 * dpr
  ctx.scale(dpr, dpr)
})

绘制文字

ctx.save()
ctx.font = 'normal normal 26px SourceHanSerifCN';
ctx.fillStyle = '#928e93';
ctx.fillText("绘制的文字内容", 88, 790);
ctx.restore();

绘制自动换行的文字

let tempText = "我是需要换行的文字\n我的内容很长很长很长很长很长"
let textList = tempText.split("\n")
let bookLength = 12
let bookSize = 36
let bookLine = 48
if(tempText.length>=50){
  bookLength = 13
  bookSize = 34
  bookLine = 46
}
if(tempText.length>=90){
  bookLength = 15
  bookSize = 30
  bookLine = 40
}
if(tempText.length>=150){
  bookLength = 17
  bookSize = 26
  bookLine = 36
}
for (let i = 0; i < textList.length; i++) {
  let item = textList[i]
  let MaxLength = 0
  let MaxIndex = 0
  let tempItem = item.split("")
  tempItem.forEach((items,index)=>{
    if (items.match(/[^\x00-\xff]/ig) != null){
      MaxLength+=2
    }else{
      MaxLength+=1
    }
    if(MaxLength<=bookLength*2){
      MaxIndex = index
    }
  })
  if (MaxLength > bookLength*2) {
    textList[i] = item.substring(0, MaxIndex);
    textList.splice(i + 1, 0, item.substring(MaxIndex, item.length))
  }
}
ctx.save()
ctx.font = "normal " + bookSize + "px 'SourceHanSerifCN'";
ctx.fillStyle = '#413e44';
let booksTop = 180
if (textList.length >= 4) {
  booksTop = 114
}
if (textList.length >= 6) {
  booksTop = 104
}
textList.forEach((item, index) => {
  ctx.fillText(item, 86, (booksTop + index * bookLine));
})
ctx.restore();

绘制矩形

ctx.save()
ctx.fillStyle = '#f0f1f1'
ctx.fillRect(435, 685, 124, 124)
ctx.restore();

绘制图片

const bg = canvas.createImage();
bg.src = "../../static/image/xxxx.png"
bg.onload = function () {
  ctx.drawImage(bg, 0, 0, 640, 865);
}

绘制用户头像(头像绘制需要先画个圆,然后在圆左上角位置开始绘制头像,画圆的时候是圆的中心点开始画的)

const avatar = canvas.createImage();
let avatorSrc = "我是头像地址"
avatar.src = avatorSrc
avatar.onload = function () {
  ctx.save()
  ctx.arc(117, 589, 29, 0, 2 * Math.PI)
  ctx.clip()
  ctx.drawImage(avatar, 88, 560, 58, 58)
  ctx.restore();
}

最好差不多了,就可以生成图片,并且对图片进行保存了

wx.canvasToTempFilePath({
  x: 0,
  y: 0,
  width: 640,
  height: 865,
  destWidth: 640 * 4,
  destHeight: 865 * 4,
  canvas: canvas,
  fileType: 'png',
  quality: 100,
  success: function (res) {
    console.log("保存图片到相册", res);
    wx.saveImageToPhotosAlbum({ //保存图片到相册
      filePath: res.tempFilePath,
      success: function () {
        wx.hideLoading()
        wx.showToast({
          title: "保存图片成功!",
          duration: 2000
        })
      },
      fail() {
        wx.showToast({
          title: "保存失败!",
          icon: 'none',
          duration: 2000
        })
        wx.hideLoading()
      }
    })
  },
  fail(e) {
    wx.hideLoading()
    console.log("失败", e)
  }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值