vue3 使用 qrcode将信息导出为二维码图片,并在图片添加自定义文字

315 阅读1分钟

一 ,下载qrcode依赖

pnpm i qrcode

二,使用qrcode将二维码的值转为canvas


import QRCode from 'qrcode'

async function handleClickExportQRcode () {
  const value =  '我是解析出二维码的内容'
  const canvas = await QRCode.toCanvas(qrLink.value)
  downloadQR2Png(canvas, '测试二维码', '测试')
}


function downloadQR2Png (canvas, fileName = '二维码图片文件名', txt = '文字内容') {
  const originalWidth = canvas.width
  const originalHeight = canvas.height
  const borderWidth = 40 // 白边宽度
  const newWidth = originalWidth + 2 * borderWidth
  const newHeight = originalHeight + 2 * borderWidth // 多出的 borderWidth 用于底部文字

  // 创建一个新的 canvas 用于添加白边和文字
  const newCanvas = document.createElement('canvas')
  newCanvas.width = newWidth
  newCanvas.height = newHeight
  const ctx = newCanvas.getContext('2d')

  // 设置背景为白色
  ctx.fillStyle = '#ffffff'
  ctx.fillRect(0, 0, newWidth, newHeight)

  // 绘制原始二维码到新的 canvas 上
  ctx.drawImage(canvas, borderWidth, borderWidth)

  // 在底部白边写入“图片”二字
  ctx.font = '18px Arial' // 设置字体样式
  ctx.fillStyle = '#45a8e2' // 设置文字颜色为黑色
  ctx.textAlign = 'center' // 设置文字居中
  ctx.fillText(txt, newWidth / 2, newHeight - 25) // 绘制文字

  // 下载新的 canvas 图像
  const url = newCanvas.toDataURL()
  const a = document.createElement('a')
  a.download = `${fileName}.png`
  a.href = url
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}