在Canvas中加载多个图像

时间:2017-08-20 17:31:15

标签: javascript html5 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方法后没有出现在画布中?

2 个答案:

答案 0 :(得分:0)

首先,你需要确定contex globalCompositeOperation,尝试将其设置为:

ctx.globalCompositeOperation='destination-over';

并确保画布的宽度和高度,它们应该大于玩家的偏移量,例如:

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

答案 1 :(得分:0)

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

例如,以下内容将加载一个图像数组,使用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.