2017-08-20 63 views
0

我在畫布上顯示圖像時遇到問題。我不明白它爲什麼只渲染一個圖像(在這種情況下是背景)。這裏是我的代碼:在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方法後不出現在畫布上?

+0

您的背景可能更大,因此通常會加載一些時間並最後繪製,其餘部分將會繪製完畢。 – ASDFGerte

+0

我想過了,所以它可能是真的。我的BG約爲125kb,播放器約爲45kb。 –

+0

當你完成加載時,你繪製圖像的方式是非典型的,會導致上述問題。以設定的順序繪製圖像,確保所有圖像都事先加載。 – ASDFGerte

回答

0

首先,你需要確保約CONTEX globalCompositeOperation,試圖將其設置爲:

ctx.globalCompositeOperation='destination-over'; 

,並確保有關畫布寬度和高度,他們應該是大於你的播放器偏移,如:

canvas.width = CANVAS_WIDTH; 
canvas.height = CANVAS_HEIGHT; 
0

如果您的介質依賴於其他介質,請在開始時加載所有介質,並等待所有介質加載後再開始使用它們。

例如,下面將加載一個圖像數組,使用一組網址創建並啓動加載。計數器在加載每個圖像時計數,當加載計數等於調用函數allLoaded的圖像數時。

const imageURL = ["foreground.jpg","background.jpg"]; // list of image URLs 
const images = []; /// array to hold images. 
var imageCount = 0; // number of loaded images; 

// function called once all images have loaded. 
function allLoaded(){ 
    // all images have loaded and can be rendered 
    ctx.drawImage(images[1],0,0); // draw background 
    ctx.drawImage(images[0],0,0); // draw foreground 
} 

// iterate each image URL, create, load, and add it to the images array 
imageURL.forEach(src => { // for each image url 
    const image = new Image(); 
    image.src = src; 
    image.onload =()=>{ 
     imageCount += 1; 
     if(imageCount === imageURL.length){ // have all loaded???? 
      allLoaded(); // call function to start rendering 
     } 
    } 
    images.push(image); // add loading image to images array 

}); 
// the image onload event will not be called until all current execution is 
// complete.