4 回答
TA贡献1804条经验 获得超2个赞
像这样
players.forEach(player => {
if (player.nick != null) {
let img = new Image(SQUARE, SQUARE)
img.onload = function() {
ctx.drawImage(img, LEFT_LINE + player.x * SQUARE, UPPER_LINE + player.y * SQUARE, this.width, this.height)
}
img.src = "sprites/player1.png"; // or `sprites/${player.image}`;
}
});
如果您有另一个图像名称数组,您可以将索引添加到 forEach :
players.forEach((player,i) => {
if (player.nick != null) {
let img = new Image(SQUARE, SQUARE)
img.onload = function() {
ctx.drawImage(img, LEFT_LINE + player.x * SQUARE, UPPER_LINE + player.y * SQUARE, this.width, this.height)
}
img.src = `sprites/${images[i]}`;
}
});
const SQUARE = 100;
const images = [
"https://via.placeholder.com/100x100?text=Image1",
"https://via.placeholder.com/100x100?text=Image2",
"https://via.placeholder.com/100x100?text=Image3"
];
const players = [
{ nick: "Fred", x: 10, y: 20 },
{ nick: "Joe", x: 20, y: 40 },
{ nick: "Sam", x: 30, y: 50 }
];
players.forEach((player, i) => {
if (player.nick != null) {
let img = new Image(SQUARE, SQUARE)
img.onload = function() {
console.log(i,player.nick,`ctx.drawImage(img, LEFT_LINE ${player.x} * SQUARE, UPPER_LINE + ${player.y} * SQUARE, ${this.width}, ${this.height})`)
}
img.src = `${images[i]}`;
}
});
TA贡献1860条经验 获得超9个赞
你可以做一个for循环
function drawPlayers() {
for (let i = 0; i < players.length; i++) {
if (players[i].nick != null) {
let playerImg = new Image(SQUARE, SQUARE)
playerImg.onload = function() {
ctx.drawImage(
playerImg,
LEFT_LINE + players[i].x * SQUARE,
UPPER_LINE + players[i].y * SQUARE,
this.width,
this.height
)
}
// if the image is fixed
playerImg.src = 'sprites/player1.png'
// else
// playerImg.src = `sprites/player${i + 1}.png`
}
}
}
TA贡献1860条经验 获得超8个赞
另一种变体:
for(let p of players){
if(p.nick){
let playerImg = new Image(SQUARE,SQUARE);
playerImg.onload = function() {
ctx.drawImage(player1Img, LEFT_LINE + p.x*SQUARE, UPPER_LINE + p.y*SQUARE, this.width, this.height)
}
playerImg.src = "sprites/player1.png"
}
}
我最近了解到的另一个功能:
for(let p of players){
if(!p.nick) continue;
let playerImg = new Image(SQUARE,SQUARE);
playerImg.onload = function() {
ctx.drawImage(player1Img, LEFT_LINE + p.x*SQUARE, UPPER_LINE + p.y*SQUARE, this.width, this.height)
}
playerImg.src = "sprites/player1.png"
}
TA贡献1858条经验 获得超8个赞
function drawPlayers() {
players.forEach((player, idx) => {
if (player.nick != null) {
// uncomment following comment block and delete this comment
/*
var img = new Image(SQUARE, SQUARE)
img.onload = () => {
ctx.drawImage(img, LEFT_LINE + player.x * SQUARE, UPPER_LINE + player.y * SQUARE, this.width, this.height)
};
img.src = "sprites/player"+(idx+1)+".png";
*/
console.log(idx, player.nick, "sprites/player"+(idx+1)+".png");
}
});
}
var players=[{nick:"abe"},{},{nick:"chuck"},{nick:"dick"}];
drawPlayers();
添加回答
举报