简体   繁体   English

JSZIP - 多个画布保存到一个 .zip 文件

[英]JSZIP - Multi canvases saved to one .zip file

I have many canvas on my page.我的页面上有很多画布。 I want to save them all to 1 .zip file (using JSZIP) on button click.我想在单击按钮时将它们全部保存到 1 个 .zip 文件(使用 JSZIP)。 I tried everything but it doesn't work :C.我尝试了一切,但它不起作用:C。 What am I missing?我错过了什么?

async function blobCalc(file) {
    const blob = await new Promise(res => file.toBlob(res));
    return blob;
}

async function genBlob(canvases) {
    const blob = await Promise.all(
        [...canvases].map(async(element)=>{
            return await blobCalc(element);
         })
     );
     return blob;
}

async function saveAs(){
    const canvas = document.querySelectorAll("canvas");
    let blobs = await genBlob(canvas);

    const zip = new JSZip();

    for(let i = 0;  i < blobs.length;i++){
        zip.file("canvas"+ i +".png", blobs[i], {base64: true});
    }

    return zip;
}

async function save(){
    await saveAs().then( async (res) => {
       await res.generateAsync({ type: "blob" }).then(function(content){
            saveAs(content, "test.zip"); });
    })
}

const btnGenerate = document.getElementById("form-btn");

btnGenerate.addEventListener('click', save);

You are overwriting the native method saveAs with your function saveAs .您正在使用函数saveAs saveAs

For completeness here's the code that works for me:为了完整起见,这是对我有用的代码:

var canvas = document.getElementById("my-canvas");
const zip = new JSZip();
canvas.toBlob(function(data) {

  zip.file("file.png", data);
  zip.file("file.txt", "another file");

  zip.generateAsync({
    type: "blob"
  }).then(function(content) {
    saveAs(content, "test.zip");
  });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM