首页 > 解决方案 > 将 url 分配给 Promise 内的 img 源后,不会触发加载事件侦听器

问题描述

我正在写一个以图像的 url 作为参数的承诺。然后我想在图像资源完全加载后做一些事情。

function retrieveImage(imageUrl) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'Anonymous';
    img.addEventListener('load', function (e) {
      // bunch of execution
      console.log('I am loaded.');
      resolve('something');
    });
    img.src = imageUrl;
  });
}

在我做了类似的事情之后,我期望:

// Load google's logo.
const loadSomeImage = retrieveImage('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');

控制台将记录“我已加载”。信息。相反,控制台没有显示任何内容。更进一步,即使在我检查了 firefox 上的网络活动面板后,promise 仍然显示为未决状态,该面板显示 http GET 状态为 200。

这是原始功能。

function retrieveImage(imageUrl) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'Anonymous';
    img.addEventListener('load', function (e) {
      // I want to draw the image into a canvas
      // and convert it into base64url.
      const canv = document.createElement('canvas');
      canv.width = this.width;
      canv.height = this.height;
      const ctx = canv.getContext('2d');
      ctx.drawImage(this, 0, 0);
      // The reason why I need set crossOrigin attr to anonymous is
      // because the following code. If I don't set that, I will get a
      // security warning and the code just doesn't proceed any further.
      resolve(canv.toDataURL());
    });
    img.src = imageUrl;
  });
}

标签: javascripthtmlpromise

解决方案


推荐阅读