Uncaught Error: Incomplete or corrupt PNG file

Uncaught Error: Incomplete or corrupt PNG file

我正在尝试将几张图片添加到 pdf 中。为此,我正在使用 jspdf 插件。我的代码如下:

document.getElementById("help").addEventListener("click",function(){
    var base1="";
    var base2="";
    var base3="";
    var doc = new jsPDF();
    var img=new Image();
    var img1=new Image();
    var img2=new Image();
    img.onload = function() {
        var canvas = document.createElement("canvas");
        ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);
        base1 = canvas.toDataURL();
    }
    img.src='/Screenshot (1).png';
    img1.onload = function() {
        var canvas = document.createElement("canvas");
        ctx = canvas.getContext('2d');
        ctx.drawImage(img1, 0, 0);
        base2 = canvas.toDataURL();
    }
    img1.src='/Screenshot (2).png';
    img2.onload = function() {
        var canvas = document.createElement("canvas");
        ctx = canvas.getContext('2d');
        ctx.drawImage(img2, 0, 0);
        base3 = canvas.toDataURL();
    }
    img2.src='/Screenshot (3).png';

    doc.addImage(base1,'PNG',20,36,100,120);
    
    doc.addImage(base2,'PNG',20,158,100,120);
   
    doc.addImage(base3,'PNG',20,281,100,120);
    doc.save("example.pdf");
})

但是当我执行代码时,我在 addImage() 中得到以下错误:

Uncaught Error: Incomplete or corrupt PNG file

我该如何解决这个问题?

编辑:实施@AKX 的解决方案后,代码可在本地机器上运行。但是在现场测试时,它会抛出这个错误:

Uncaught (in promise) Event {isTrusted: true, type: 'error', target: null, currentTarget: null, eventPhase: 0, …}

您没有等待所有图像加载。您可以重构使用 a promisified function to load an image and turn it into a data URI (though according to the docs for jspdf, a HTMLImageElement would also do, so you could skip the canvas bit), and then turn your handler into an async function 的东西,以便于仅 await 处理所有负载。

function loadImageAsDataURL(url) {
  return new Promise((resolve, reject) => {
    var img = new Image();
    img.onload = function () {
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
      resolve(canvas.toDataURL());
    }
    img.onerror = reject;
    img.src = url;
  });
}

document.getElementById('help').addEventListener('click', async function () {
  // Load all images first...
  var base1 = await loadImageAsDataURL("/Screenshot (1).png");
  var base2 = await loadImageAsDataURL("/Screenshot (2).png");
  var base3 = await loadImageAsDataURL("/Screenshot (3).png");
  // ... and then generate the PDF.
  var doc = new jsPDF();
  doc.addImage(base1, 'PNG', 20, 36, 100, 120);
  doc.addImage(base2, 'PNG', 20, 158, 100, 120);
  doc.addImage(base3, 'PNG', 20, 281, 100, 120);
  doc.save('example.pdf');
})