Aurore
Aurore

Reputation: 746

Add random image to page at user clicked position

I'm trying to write a script that picks a random image in an array and display it at the mouse x,y position. Also, when the image is shown, you can click somewhere else to add a new one. So you can fill the whole page with random cat images if you want.

document.onclick = userClicked;
    function userClicked() {
    var x = event.clientX;
    var y = event.clientY;
    var cat = document.getElementById("cat1");
    cat.style.display = '';
    cat.style.position = 'absolute';
    cat.style.left = x - cat.width / 2 + 'px';
    cat.style.top = y - cat.height / 2 + 'px';

}
.image{
  width:100px;
  height:auto;
}
#cat1{
  background-color:red;
  width:100px;
  height: auto;
}
<div class="container">
        <img alt="catAppear" class ="image" id="cat1" style="display: none" src="https://www.coopmcs.com/dotclear/public/chat.png"/>
  <img alt="catAppear"  class ="image" id="cat2" style="display: none" src="https://static.toiimg.com/thumb/msid-67586673,width-800,height-600,resizemode-75,imgsize-3918697,pt-32,y_pad-40/67586673.jpg"/>
    </div>
</div>

Upvotes: 0

Views: 393

Answers (2)

s.kuznetsov
s.kuznetsov

Reputation: 15213

var img_cats = ['https://www.coopmcs.com/dotclear/public/chat.png',
'https://static.toiimg.com/thumb/msid-67586673,width-800,height-600,resizemode-75,imgsize-3918697,pt-32,y_pad-40/67586673.jpg'
        ]

document.onclick = userClicked;

    function userClicked() {
    var x = event.clientX;
    var y = event.clientY;
    var cat = document.getElementById("cats");
    cat.src = img_cats[Math.floor(Math.random() * img_cats.length)];
    cat.style.display = '';
    cat.style.position = 'absolute';
    cat.style.left = x - cat.width / 2 + 'px';
    cat.style.top = y - cat.height / 2 + 'px';

}
.image{
  width:100px;
  height:auto;
}
#cat1{
  background-color:red;
  width:100px;
  height: auto;
}
<div class="container">
        <img alt="catAppear" class="image" id="cats" src="" style="display: none"/>
    </div>
</div>

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89314

You can store all the possible image sources in an array, pick a random element each time, and append a new <img> element with the chosen source to the document.

const srcs = ['https://i.pinimg.com/originals/7a/af/0f/7aaf0f1d48f57b7779c0fbcf103c2d0f.jpg', 'https://www.coopmcs.com/dotclear/public/chat.png'];
document.onclick = userClicked;
function userClicked() {
    var x = event.clientX;
    var y = event.clientY;
    const img = document.createElement('img');
    img.classList.add('image');
    img.src = srcs[Math.floor(Math.random() * srcs.length)];
    img.width = '150';
    img.height = '150';
    img.onload = function(){
      img.style.left = x - img.width / 2 + 'px';
      img.style.top = y - img.height / 2 + 'px';
    }
    document.body.appendChild(img);
}
.image {
  position: absolute;
}

Upvotes: 2

Related Questions