项目场景:
我们在后台pc端中 偶尔会需要用到 通过生成二维码的功能,但是只生成展示或许还是不够的 还需要导出下载二维码,算了不编了 只当个人笔记 了 语法为vue3
效果图:
解决方案:
1、导入2个依赖 一个是下载为压缩包的 一个是 html转图片的
npm install jszip
npm install html2canvas
2、核销方法
//下载二维码
function qrCodeDownload() {
//遮罩层
const loading = ElLoading.service({
lock: true,
text: "下载中...",
background: "rgba(0, 0, 0, 0.7)",
spinner: "none",
});
setTimeout(() => {
const zip = new JSZip();
qRCodeList.value.forEach((item, index) => {
const tempDiv = document.createElement("div");
tempDiv.style.display = "flex";
tempDiv.style.flexDirection = "column";
tempDiv.style.alignItems = "center";
tempDiv.style.width = "300px";
document.body.appendChild(tempDiv);
const qrCodeCanvas = document.createElement("canvas");
tempDiv.appendChild(qrCodeCanvas);
QRCode.toCanvas(qrCodeCanvas, item.qrCode, { width: 250 }, (error) => {
if (error) {
console.error("Error:", error);
return;
}
const field1Element = document.createElement("p");
field1Element.textContent = "充电编号:" + item.pileNo;
field1Element.style.marginBottom = "5px";
field1Element.style.marginTop = "-5px";
tempDiv.appendChild(field1Element);
const field2Element = document.createElement("p");
field2Element.textContent = item.pileCode;
field2Element.style.marginTop = "5px";
tempDiv.appendChild(field2Element);
html2canvas(tempDiv, { useCORS: true }).then((canvas) => {
const imageData = canvas.toDataURL("image/png").split(",")[1];
zip.file(`${item.pileCode}.png`, imageData, {
base64: true,
});
document.body.removeChild(tempDiv);
if (index === qRCodeList.value.length - 1) {
zip.generateAsync({ type: "blob" }).then((content) => {
const link = document.createElement("a");
link.href = URL.createObjectURL(content);
link.download =
"电桩二维码_" + new Date().toLocaleDateString() + ".zip";
link.click();
loading.close();
});
}
});
});
});
}, 500);
}