我试图在for循环中使用图像加载器绘制图像。它仅在最后一次迭代中绘制所有图像。
在控制台中它没有显示draw -> 0
或draw -> 1
它只是显示draw -> 2
谢谢你的帮助!!
这是我的代码块:
// For every player run iteration
var pos="";
var iter="";
for (var i = 0; i < item.length; ++i) {
// Position for players on account screen
if(i == 0){ pos = "61px"; iter = 0; console.log("pos 0 -> " + iter);}
if(i == 1){ pos = "168px"; iter = 1; console.log("pos 1 -> " + iter);}
if(i == 2){ pos = "275px"; iter = 2; console.log("pos 2 -> " + iter);}
console.log(i);
console.log("pos -> " + pos);
console.log("iter -> " + iter);
// Gets player name from string
let player = item[i].match( /([A-Z])\w+/g );
// Create player div for mouse interaction
let player_el = $('<div class="cursor player" id="player'+ player +'"></div>');
$("#can_wrapper").append(player_el);
$("#player"+ player).css({"position": "absolute", "height": "50px", "width": "50px", "left": ""+ pos +"", "top": "271px", "cursor": "grab", "cursor": "-webkit-grab"});
// Get player name for hover action
let player_name_el = player;
document.styleSheets[0].addRule('#player'+ player +':hover::after','content: "'+player_name_el+'";');
/**
* Promisify loading an image
* @param {String} imagePath The web location of the image
* @returns {Promise} A Promise that will resolve to an Image
*/
function loadImage(imagePath) {
return new Promise((resolve, reject) => {
let image = new Image();
image.addEventListener("load", () => {
resolve(image);
});
image.addEventListener("error", (err) => {
reject(err);
});
image.src = '../interface/images/body/' + imagePath;
});
}
let imageSources = ['v1456.png', 'vbody0.png','vhead14.png','v1960.png','v578.png','v1221.png', 'v3063.png']; // url and order
Promise
.all(imageSources.map(ii => loadImage(ii)))
.then((images) => {
images.forEach((image) => {
if (iter == 0) { ctx.drawImage(image, 60, 270); console.log("draw -> 0");}
if (iter == 1) { ctx.drawImage(image, 167, 270); console.log("draw -> 1");}
if (iter == 2) { ctx.drawImage(image, 274, 270); console.log("draw -> 2");}
console.log(iter);
});
}).catch((err) => {
console.error(err);
});
}
我建议在循环外移动function loadImage
如果你使用let
而不是var
并在for循环中移动pos和iter的声明,那么它应该工作
function loadImage(imagePath) {
return new Promise((resolve, reject) => {
let image = new Image();
image.addEventListener("load", () => {
resolve(image);
});
image.addEventListener("error", (err) => {
reject(err);
});
image.src = '../interface/images/body/' + imagePath;
});
}
for (let i = 0; i < item.length; ++i) {
let pos="";
let iter="";
// rest of your code remains unchanged
}