您好,我创建了一个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;
});
}发布于 2020-01-12 12:40:11
在我使用promise获取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">
发布于 2020-01-12 15:49:53
这是我的基本调用块,但它在循环中
caller(logo, 150, 150).then
(function (response) {
console.log("Success!", response);
base64Urls.push(response);});
https://stackoverflow.com/questions/59700845
复制相似问题