需求
工作中有一个将地址生成二维码,再将二维码与一张背景图合成一张海报的需求
实现
1.生成二维码
//下载插件实现
import QRCode from 'qrcode'
//生成二维码的方法 url-地址;picUrl-背景图片地址;
getQRpic(url, picUrl) {
let that = this
QRCode.toDataURL(url)
.then((qrUrl) => {
that.getPosterPic(qrUrl, picUrl)
})
.catch((err) => {
console.error(err)
})
},
2.合成一张图片
getPosterPic(qrUrl, picUrl) {
let that = this
function drawAndShareImage() {
var canvas = document.createElement('canvas')
var myImage = new Image()
myImage.src = picUrl //背景图片
myImage.crossOrigin = 'Anonymous'
myImage.onload = function () {
canvas.width = myImage.width
canvas.height = myImage.height
var context = canvas.getContext('2d')
context.rect(0, 0, canvas.width, canvas.height)
context.fillStyle = '#fff'
context.fill()
context.drawImage(myImage, 0, 0, myImage.width, myImage.height)
var myImage2 = new Image()
myImage2.src = qrUrl //二维码图片
myImage2.crossOrigin = 'Anonymous'
myImage2.onload = function () {
let x = 515 // myImage.width - myImage2.width - 34
let y = 1112 // myImage.height - myImage2.height - 10
// console.log(x, y, (220 / 750) * myImage.width)
context.drawImage(myImage2, x, y, 220, 220)
var base64 = canvas.toDataURL('image/png') //"image/png" 这里注意一下
const a = document.createElement('a')
a.href = base64
a.setAttribute('download', '图片名称')
a.click()
}
}
}