一 ,下载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
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)
ctx.drawImage(canvas, borderWidth, borderWidth)
ctx.font = '18px Arial'
ctx.fillStyle = '#45a8e2'
ctx.textAlign = 'center'
ctx.fillText(txt, newWidth / 2, newHeight - 25)
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)
}