我在畫布上顯示圖像時遇到問題。我不明白它爲什麼只渲染一個圖像(在這種情況下是背景)。這裏是我的代碼:在Canvas中加載多個圖像
// ... Some code here
this.createBackground(canvas, config);
this.createPlayer(canvas, config);
}
createBackground(element, config) {
const canvas = element;
const ctx = canvas.getContext("2d");
const bg = new Image();
bg.src = "./img/" + config.bg;
bg.onload =() => {
ctx.drawImage(bg, 0, 0, config.width, config.height);
}
return bg;
}
createPlayer (element, config) {
const canvas = element;
const ctx = canvas.getContext("2d");
const player = new Image();
player.src = "./img/" + config.character + "/Run1.png";
player.onload =() => {
ctx.drawImage(player, 70, 310, player.width/3, player.height/3);
}
return player;
}
爲什麼我的玩家在bg方法後不出現在畫布上?
您的背景可能更大,因此通常會加載一些時間並最後繪製,其餘部分將會繪製完畢。 – ASDFGerte
我想過了,所以它可能是真的。我的BG約爲125kb,播放器約爲45kb。 –
當你完成加載時,你繪製圖像的方式是非典型的,會導致上述問題。以設定的順序繪製圖像,確保所有圖像都事先加載。 – ASDFGerte