javascript - 图像加载未在承诺内触发
问题描述
您好,我创建了一个 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;
});
}
解决方案
在我使用该承诺获取 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">
推荐阅读
- javascript - 模拟单击单选按钮
- augmented-reality - 具有 2 个场景的 Reality Composer 项目文件会在 Xcode 中播放吗?
- github - 在 github 中启用提交按钮
- ios - 以编程方式呈现 UIViewController
- android - 为什么 android.bluetooth.BluetoothAdapter#listenUsingL2capOn(int) 无法访问?
- c++ - 我想使用 hashmap 打印不重复的数字;
- python - 如何检查 discord.py 中的文件扩展名
- c# - 添加 WCF 服务选项在 VisualStudio 2017 中不可用
- python - Tensorflow 最大递归深度仅在导入时超过
- r - 在 R 中创建一个相关列