HTML元素转化成图片批量下载

项目场景:

我们在后台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);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值