javascript - 将 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;
});
}
解决方案
推荐阅读
- android - android/view/view$on 未处理的 keyevent 监听器错误
- javascript - 理解 HTML 中的 Jquery
- python - 如何删除行 pandas df
- vba - Word VBA 将长日期转换为短日期
- mongodb - Node.js 应用程序无法使用 Kubernetes 连接到 MongoDB Docker 容器
- c# - 如何使用 JsonSerializerSettings 和 UseSnakeCasePropertyNames
- python - 在 Python 中实现自定义 Str 或 Buffer
- java - 单击按钮会导致应用程序崩溃 Android Studio
- go - YAML 修改别名序列元素
- javascript - AJAX 语法错误:无效字符