两个不同的图像onLoad

时间:2014-08-11 03:18:06

标签: javascript html5 canvas

目前,每次运行动画时,我只有一张onLoad图像。

var imgFish = new Image();
imgFish.onload = init;
imgFish.src = 'Image';

我尝试同时加载两个或更多不同的图像。

当我按下'添加一条鱼'时,我只有一条橙色的鱼在画布上移动!按钮。我想让更多不同的鱼在画布上游泳。我创建了另一个名为“添加不同颜色的鱼!”的按钮,我想添加一条鱼,但是使用相同的代码添加不同的图像以允许鱼在画布上进行动画制作。

任何人都知道如何实现它?

2 个答案:

答案 0 :(得分:1)

这是一个通用的图像加载器,可以预加载所有图像,然后调用start()

// image loader

// put the paths to your images in imageURLs[]
var imageURLs=[];  
// push all your image urls!
imageURLs.push("");

// the loaded images will be placed in images[]
var imgs=[];

var imagesOK=0;
loadAllImages(start);

function loadAllImages(callback){
    for (var i=0; i<imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function(){ 
            imagesOK++; 
            if (imagesOK>=imageURLs.length ) {
                callback();
            }
        };
        img.onerror=function(){alert("image load failed");} 
        img.crossOrigin="anonymous";
        img.src = imageURLs[i];
    }      
}

function start(){

    // the imgs[] array now holds fully loaded images
    // the imgs[] are in the same order as imageURLs[]

}

答案 1 :(得分:1)

请参阅http://jsfiddle.net/qx3tq5bL/1/

您的代码需要一个图像对象才能在Fish的构造函数中创建一条新鱼。因此,您需要做两件事:

首先,创建一个新的图像对象,指向不同颜色的鱼的不同图像

var imgFish2 = new Image();
imgFish2.onload = init;
imgFish2.src = 'https://dl.dropboxusercontent.com/s/0q7o0i23xmz719m/FishStrip.png';

其次,将函数绑定到函数init中的新按钮:

document.getElementById("button1").onclick = function() {
  // create another fish using the Fish class
  var anotherFish = new Fish(xPos, yPos, speedX, speedY, imgFish2, frameWidth, frameHeight);
  // put this new fish into the fishes[] array
  fishes.push(anotherFish) ;
  // make it start changing directions
  anotherFish.changeDirection();
  // draw this new fish
  anotherFish.drawFish();
}