The code below randomizes image locations on a webpage. Is there any way I could alter the code to prevent the script from using the same image more than once? As of now, it will sometimes reuse the same photo multiple times on the page load, and I would like to prevent this so that only one of each photo gets used.
In other words, is there any way to randomly populate image locations on the webpage without repeating the same image but also using them all?
Let me know if you can help. :)
const imgPoss = [];
let maxX, maxY;
function placeImg() {
const NUM_OF_IMAGES = 23; // set this to however images you have in the directory.
const START_OF_IMAGES = 1;
const randImg = Math.round(Math.random() * NUM_OF_IMAGES + START_OF_IMAGES);
const imgSrc = 'https://elimcgehee.github.io/staticimages/gallery/' + randImg.toString() + '.png';
const {random: r} = Math;
const x = r() * maxX;
const y = r() * maxY;
if(!isOverlap(x,y)) {
var link = `<img class="random" style="left: ${x}px; top: ${y}px;" src="${imgSrc}" />`;
var bodyHtml = document.body.innerHTML;
document.body.innerHTML = bodyHtml + link;
imgPoss.push({x, y}); // record all img positions
}
}
function isOverlap(x, y) { // return true if overlapping
const img = {x: 128, y:160};
for(const imgPos of imgPoss) {
if( x>imgPos.x-img.x && x<imgPos.x+img.x &&
y>imgPos.y-img.y && y<imgPos.y+img.y ) return true;
}
return false;
}
onload = function() {
maxX = innerWidth - 128;
maxY = innerHeight - 160;
setInterval(placeImg, 10);
}
onresize = function() {
maxX = innerWidth - 128;
maxY = innerHeight - 160;
}