react 项目使用qrcode.react生成二维码,并提供批量下载

react 项目使用qrcode.react二维码,并提供批量下载

1.使用的插件
npm install qrcode.react; – 生成二维码插件
npm install jszip; – 提供zip压缩
npm install file-saver; – 文件下载
2.数据渲染
在这里插入图片描述
页面根据state数据渲染生成二维码,然后 放入div中进行隐藏,由点击事件clickDownload触发下载
render() {
<div style = {{ display: ‘none’}}>
{this.createQRCode()}


<Button size=‘small’ type=“primary” style={{ float: ‘right’ }} onClick={this.clickDownload.bind(this)}>
{‘批量下载二维码’}


}
}
3.下载点击事件
clickDownload = () =>{
const canvas = document.getElementsByTagName(‘canvas’);
const zip = new JSZip();
if(null != canvas && canvas.length > 0){
for(let i = 0; i < canvas.length; i++){
const canvan = canvas[i];
const context = canvan.getContext(‘2d’);
// 此处是重新置画布大小
const newCanvan = document.createElement(‘canvas’);
const newContext = newCanvan.getContext(‘2d’);
newCanvan.width = 300;
newCanvan.height = 220;
newContext.drawImage(canvan, 40, 30);
//此处下载图片实际尺寸
canvan.width = 508;
canvan.height = 224;
//此处是设置下载图片的背景色和其背景大小,不设置的话图片放在桌面背景是透明
context.fillStyle = ‘white’;
context.fillRect(0,0,508,224);
context.drawImage(newCanvan, 0, 0);
context.fillStyle = ‘rgb(0,0,0)’ // 分配颜色
context.font = ‘700 20px Arial’ // 文本大小, 字体
const name = canvan.getAttribute(“name”);
if (!isEmptyValue(name)) {
const names = name.split(’\n’);
let height = 60;
for(let j = 0; j < names.length; j++){
const text = names[j];
context.fillText(text, 220, height); // 绘制文本(text, x, y)
height = height + 40;
}
}
// substring(22) 是去掉base64头部,放到jszip对象里
zip.file(name + “.png”, canvan.toDataURL().substring(22), {
base64: true,
});
}
// 3. 以二进制形式保存、并且通过file-saver下载到本地
zip.generateAsync({ type: “blob” }).then(function (content) {
FileSaver.saveAs(content, “二维码.zip”);
});
}
}

  • 14
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值