Two different images onLoad

Currently, I only have one onLoad image every time I run the animation.

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

I am trying to upload two or more different images at the same time.

I have only one orange fish moving around the canvas when I click on "Add fish!". button. I want to make more different fish swimming on canvas. I created another button called “Add another color fish!”, I want to add a fish, but with a different image with the same code, so that the fish can animate on the canvas.

Does anyone know how I can achieve this?

-1
source share
2 answers

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

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

First create a new image object pointing to a different image of fish of different colors

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

Secondly, bind the function to your new button in the init function:

 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(); } 

+1
source

This uses a generic image downloader 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[] } 
+1
source

Source: https://habr.com/ru/post/1239820/


All Articles