在Vue中用canvas实现二维码和图片合成海报的方法
在项目中经常会遇到需要将不同的二维码放到一张通用图片上,提供用户下载
简单来说,就是利用canvas将同等比例的二维码在图片上叠加,生成海报
1.设置相应比例
一般来说海报背景都是固定的,可以直接放在public文件夹,二维码可根据后台返回数据,也可用canvas生成,在此不多赘述
importposterBgImgfrom'../public/images/poster_bg.png';//海报底图
importqrcodeImgfrom'../public/images/qrcode.png';//二维码
exportdefault{
name:'qrcode-in-poster',
data(){
return{
posterBgImg,
qrcodeImg,
posterSize:930/650,//海报高宽比例
qrCodeSize:{//二维码与海报对应比例=》用于设置二维码在海报中的位置
width:270/650,
height:270/930,
left:190/650,
top:448/650
},
poster:'',//合成图片
}
}
};
2.获取屏幕宽度
限定移动端最大宽度为480px
computed:{
screenWidth(){
letw=document.body.clientWidt||document.documentElement.clientWidth||375;
returnw>480?480:w;
}
};
3.组合图片
methods:{
combinedPoster(_url){
letthat=this,
qrcode=this.qrcodeImg;//二维码地址
console.log("opendraw:",_url,qrcode)
letbase64='',
canvas=document.createElement('canvas'),
ctx=canvas.getContext("2d"),
_w=this.screenWidth*2,//图片宽度:由于手机屏幕时retina屏,都会多倍渲染,在此只设置2倍,如果直接设置等于手机屏幕,会导致生成的图片分辨率不够而模糊
_h=this.posterSize*_w,//图片高度
_qr_w=this.qrCodeSize.width*_w,//二维码宽=比例*宽度
_qr_h=this.qrCodeSize.height*_h,//二维码高=比例*高度
_qr_t=this.qrCodeSize.top*_w,//二维码顶部距离=比例*宽度
_qr_l=this.qrCodeSize.left*_w;//二维码左侧距离=比例*宽度
//设置canvas宽高
canvas.width=_w;
canvas.height=_h;
ctx.rect(0,0,_w,_h);
ctx.fillStyle='#fff';//填充颜色
ctx.fill();
//迭代生成:第一层(底图)+第二层(二维码)
//file:文件,size:[顶部距离,左侧距离,宽度,高度]
let_list=[
{
file:_url,
size:[0,0,_w,_h]
},{
file:qrcode,
size:[_qr_l,_qr_t,_qr_w,_qr_h]
}
];
//开始绘画
letdrawing=(_index)=>{
//判断当前索引=》是否已绘制完毕
if(_index<_list.length){
//等图片预加载后画图
letimg=newImage(),
timeStamp=newDate().getTime();
//防止跨域
img.setAttribute('crossOrigin','anonymous')
//链接加上时间戳
img.src=_list[_index].file+'?'+timeStamp
img.onload=function(){
//画图
ctx.drawImage(img,..._list[_index].size)
//递归_list
drawing(_index+1)
}
}else{
//生成图片
base64=canvas.toDataURL("image/png")
if(base64){
//赋值相应海报上
this.$set(that,'poster',base64)
}
}
}
drawing(0)
}
};
mounted(){
//需要合成海报的图片
this.draw(this.posterBgImg)
}
4.下载
点击下载合成图片
methods:{
handleDownload(){
if(this.poster){
leta=document.createElement("a");
a.setAttribute("download","海报下载-"+(newDate().getTime()));
a.href=this.poster
a.click()
}else{
console.log("海报不存在,请重新生成!")
}
}
}
tips:不适用于微信浏览器,只能提示用户长按保存。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。