This question already has answers here:
Drawing image on canvas in loop not working
                            
                                (2个答案)
                            
                    
                    
                        Check if Images are loaded before gameloop
                            
                                (1个答案)
                            
                    
                2年前关闭。
        

    

我在画布上显示图像时遇到问题。我不明白为什么它只渲染一张图像(在这种情况下是背景)。这是我的代码:

    // ... 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方法后我的播放器没有出现在画布上?

最佳答案

如果您有依赖于其他媒体的媒体,请在开始时加载所有媒体,然后等待所有媒体加载完毕,然后再开始使用它们。

例如,以下将使用一组URL来创建并开始加载图像,以加载图像数组。计数器会在加载每个图像时对它们进行计数,当加载计数等于图像数量时,将调用函数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.

09-10 05:04
查看更多