首页 > 解决方案 > 图像加载未在承诺内触发

问题描述

您好,我创建了一个 Promise 并从循环中递归调用它来填充一个数组,但是 onload 永远不会触发,因此永远不会解决这个 Promise。

谁能看到我做错了什么?

function imageResizeToDataUriPromise(url, width, height) {

    return new Promise(function (resolve, reject) {


        var img = new Image();
        img.setAttribute('crossOrigin', 'anonymous');

        img.onload = function () {

             var imgWidth = img.naturalWidth;
             var imgHeight = img.naturalHeight;

             var result = _scaleImage(imgWidth, imgHeight, width, height, true);
             //create an off-screen canvas
             var canvas = document.createElement('canvas');
             var ctx = canvas.getContext('2d');

             canvas.width = result.width;
             canvas.height = result.height;

             //draw source image into the off-screen canvas:
             ctx.drawImage(img, 0, 0, result.width, result.height);

            resolve(canvas.toDataURL());

         };

        img.src = url;

    });
}

标签: javascriptpromiseonload

解决方案


在我使用该承诺获取 URL 并将其设置为图像元素之后,它就可以工作了……不确定您将如何使用返回的数据 URL。一个可能的问题是:您能否检查您的图像源是否为您提供图像。(仔细检查开发人员工具中的网络选项卡)。

function imageResizeToDataUriPromise(url, width, height) {

  return new Promise(function(resolve, reject) {
    var img = new Image();
    img.setAttribute('crossOrigin', 'anonymous');

    img.onload = function() {
      console.log("IMG ONLOAD handler invoked");
      var imgWidth = img.naturalWidth;
      var imgHeight = img.naturalHeight;

      var result = img;

      //create an off-screen canvas
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');

      canvas.width = result.width;
      canvas.height = result.height;

      //draw source image into the off-screen canvas:
      ctx.drawImage(img, 0, 0, result.width, result.height);

      ctx.fillStyle = "white";
      ctx.font = '21px sans-serif';
      ctx.fillText('Hello world', 21, 51);

      resolve(canvas.toDataURL());
    };

    img.src = url;

  });
}

imageResizeToDataUriPromise("https://i.imgur.com/j7Ie7pg.jpg", 100, 100)
  .then(url => document.querySelector("#an-image").src = url);

console.log("Promise obtained");
<img id="an-image">


推荐阅读