当前位置: 首页 > Web前端 > HTML5

Canvas实现二维码和图片合成

时间:2023-04-05 00:15:45 HTML5

在以前的版本中,街道上有需求。用url生成一个二维码,然后再和另一张图片结合起来拍一张你的照片。思路是用jr-qrcode从url生成data:base64供img使用,然后用canvas来两张图片合成一张图片遇到的问题生成图片后发现图片模糊。解决方案是将画布的大小加倍,并将其他参数加倍。jr-qrcode可以使用npminstall--savejr-qrcode安装这个包的作用是将img的src的text转为data:base64。代码如下importReact,{Component}from'react'constqrcode=require('jr-qrcode')constloadImg=(src)=>{constpaths=Array.isArray(src)?来源:[来源];const承诺=[];paths.forEach((path)=>{promise.push(newPromise((resolve,reject)=>{letimg=newImage();img.crossOrigin="Anonymous";img.src=path;img.onload=()=>{resolve(img);};img.onerror=(err)=>{console.log('图片加载失败')}}))});返回Promise.all(promise);}constgetImageData=(url,src)=>{constimgsrc=qrcode.getQrBase64(url)letcanvas=document.createElement('canvas')constwidth=document.documentElement.clientWidthconstheight=document.documentElement.clientHeightcanvas.width=width*2canvas.height=height*2letctx=canvas.getContext("2d")loadImg([imgsrc,src]).then(([img1,img2])=>{ctx.drawImage(img2,0,0,width*2,height*2)ctx.drawImage(img1,width-80,height*2-220,200,160)ctx.fillStyle='rgba(0,0,0,0.3)';ctx.fillRect(width-80,height*2-60,200,40);ctx.save()ctx.font="28px宋体"ctx.fillStyle='#fff';ctx.fillText('长按识别二维码',width-80,height*2-30,200,160)letimageURL=canvas.toDataURL("image/png")document.getElementById('mix_img').setAttribute('src',imageURL)})}exportdefaultclassQRcodeextendsComponent{render(){const{url,picSrc}=this.propsgetImageData(url,picSrc)返回(

)}}