我正在写一个承诺,要求以图片的网址作为修饰。然后,在图像资源完全加载后,我想做些什么。
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;
});
}