vendredi 23 septembre 2016

JavaScript Get a Random Image in a for loop

So I created a for loop which creates (determining on a textfield) a number of images.

E.g. I type "23" in the textfield and on a button click it displays 23 images randomly placed on the screen.

for(i=0; i < box2; i++) {

     this.y = Math.floor(Math.random() * 100) + 1;
     this.x = Math.floor(Math.random() * 100) + 1;

     this.img = document.createElement("img");
     this.img.src = sourceArray[num];
     this.img.setAttribute("height", "100px");
     this.img.style.position = "absolute";
     this.img.style.top = this.y + "vh";
     this.img.style.left = this.x + "vw";
     this.img.addEventListener("click", Remove);

     document.getElementById("bildausgabe").appendChild(this.img);

}

I also already have an array to pick 1 out of 3 random images which works fine, but it will only display 1 of the 3 for all images. When I reload it will pick another one from the list.

 var sourceArray = ["strand.jpg","weg.jpg","haengematte.jpg"];
 var num = Math.floor(Math.random() * 3);

How can I change it that it displays all 3 images randomly?

e.g. I type "12", click the button and get 12 images randomly from the given 3 sources.




Aucun commentaire:

Enregistrer un commentaire