I am looking to add a function to the code below... Currently, the code takes an image from a single source and randomly places the images all around the web page.
I would like any help with modifying the code so that it uses images from a directory of photos that I have. I would like to use all of the photos from the directory individually, and not just a singular photo. :)
Let me know if you might know how to do this.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>page</title>
<link rel="stylesheet" href="assets/css/style.css">
<script src="assets/js/script.js"></script>
<!-- <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script> -->
</head>
<body>
<div class="random">img 1</div>
<div class="random">img 2</div>
<div class="random">img 3</div>
<div class="random">img 4</div>
<div class="random">img 5</div>
<div class="random">img 6</div>
<div class="random">img 7</div>
<div class="random">img 8</div>
<div class="random">img 9</div>
<div class="random">img 10</div>
<div class="random">img 11</div>
<div class="random">img 12</div>
</body>
</html>
CSS:
* {
margin:0;
padding:0;
box-sizing: border-box;
}
html, body {
height: 100%;
}
body {
margin: 0;
width: 100%;
}
.random {
position: absolute;
width: 128px;
height: 160px;
}
JS:
const imgPoss = [];
let maxX, maxY;
function placeImg() {
const NUM_OF_IMAGES = 90; // set this to however images you have in the directory.
const randImg = Math.random() * NUM_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;
}