Two different image onLoad

家住魔仙堡 提交于 2020-01-14 06:51:10

问题


Currently I only have one image onLoad everytime when i run my animation.

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

I'm try to make two or more different image to load at the same time.

I have only one orange fish moving on the canvas when i press on the 'Add a fish!' button. I want to make more different fish swimming on the canvas too. I have created another button called 'Add a different color fish!', I want to add a fish but with a different image with the same code to allow the fish to animation on the canvas.

Anyone knows how can i achieve it?


回答1:


see http://jsfiddle.net/qx3tq5bL/1/

Your code requires a image object to create a new fish in the constructor of Fish. Thus you need to do 2 things:

First, Create a new image object pointing to a different image of a fish of different color

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

Second, Bind function to your new button in function 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();
}




回答2:


Here's a generic image loader that preloads all your images and then calls 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[]

}


来源:https://stackoverflow.com/questions/25235427/two-different-image-onload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!