Add random image to page at user clicked position - javascript

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>

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

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>

Related

Move image in every click javascript

I try to move the image in every click but it just move one time.See the code:
<img id="myImg" src="">
<script>
function move() {
var img = document.getElementById("myImg")
img.style.left += "2px";
}
</script>
<button onclick="move()"></button>
Anyone knows how to make it work?
When you get the value of left property, it looks like this: 0px. It's a string. So if you want to calculate it, you need to parse it to a number. Before doing that, you can split px part to get the number.
img {
position: absolute;
width: 150px;
height: 100px;
left: 0px;
}
button {
margin-top: 100px;
}
<img id = "myImg" src = "https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80">
<script>
function move(){
var img = document.getElementById("myImg");
img.style.left = +img.style.left.substring(0, img.style.left.length - 2) + 2 + 'px';
}
</script>
<button onclick = "move()">Move</button>
This line
img.style.left += "2px";
produces invalid CSS. You want to extract the integer each time, add 2, then add the "px" unit back in.
const img = document.getElementById("myImg")
function move() {
img.style.marginLeft = img.style.marginLeft ? parseInt(img.style.marginLeft, 10) + 2 + "px" : "2px"
}
<img id="myImg" src="https://placekitten.com/200/200">
<button onclick="move()">Move Image</button>
This is a very clumsy way to move an image. Please educate yourself about canvas object. But as you are a begginer and may just need a quick fix, here's a way to get your code working:
<img id = "myImg" style="width: 100px; height: 100px;" src ="https://upload.wikimedia.org/wikipedia/en/thumb/e/ec/Soccer_ball.svg/600px-Soccer_ball.svg.png">
<script>
var margin = 0;
function move(){
var img = document.getElementById("myImg")
margin += 2;
img.style.marginLeft = margin + "px";
}
</script>
<button onclick = "move()" >Move</button>
if you want to move image then you could move it either right or left for that try to fix your code at left - px
<img id = "myImg" src = "">
<script>
function move(){
var img = document.getElementById("myImg")
img.style.left += "2px";
}
function moveleft() {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
</script>
<button onclick = "moveleft();">

For Loop not working and cloning Javascript

I've tried all sorts of things to figure out why my code isn't however, I can't seem to find out why. `
var numberOfFaces = 5;
var theleftside = document.getElementById ("leftSide");
var top_position = Math.floor((Math.random() * 400) + 1);
var left_position = Math.floor((Math.random() * 400) + 1);
var theRightSide = document.getElementById("rightSide");
function generatefaces () {
for (var i = 1; i < numberOfFaces; i++) {
var img = document.createElement("img");
img.src = "smile.png";
img.style.top = top_position + "px";
img.style.left = left_position + "px";
theleftside.appendChild(img);
}
}
<style media="screen">
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 2px solid black;
}
</style>
<h1>The Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
`
I am trying to generate 5 images (smiley faces) on the lefside div at different positions, then trying to clone it to the right hand side,
I'm new with JS, so hints and tips would be much appreciated.
Because you just implemented a function but did not call it. Try adding
generatefaces();
at the end.
Two fold firstly you need to, as burkay says, call the function generatefaces().
Secondly you need to create a second element for the right side using img.cloneNode(true) this creates a duplicate so you can then append that to the right side.
Also you are generating the random position outside of the loop so the same random position is used for each img you instead need to create a random position for every img by moving it inside the loop.
Example:
var numberOfFaces = 5;
var theleftside = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");
// You need to call this function
generatefaces()
function generatefaces() {
for (var i = 1; i < numberOfFaces; i++) {
// Generate the new random position for each img
var top_position = Math.floor((Math.random() * 400) + 1);
var left_position = Math.floor((Math.random() * 400) + 1);
var img = document.createElement("img");
// The location of your face image
img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/54/Emojione_1F60E.svg/64px-Emojione_1F60E.svg.png";
img.style.top = top_position + "px";
img.style.left = left_position + "px";
// Creates a duplicate version of the image
var imgright = img.cloneNode(true);
theleftside.appendChild(img);
// Appends the duplicate image to the right side
theRightSide.appendChild(imgright);
}
}
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 2px solid black;
}
<h1>The Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
Hope this helps!

JavaScript function only affects first div with class

I have part of a game where the cursor is supposed to "slow down" when it passes over certain divs. I'm using a function that can detect a collision with the div. This works fine when the cursor meets the first div, but it doesn't work at all on the second div.
Check out this jsFiddle for a better idea of what I'm talking about. Pass the cursor over the first white block (class='thing') on the left and it slows down. Pass the cursor over the other block (also class='thing'), and nothing happens. I need this collision function to work on all divs where class='thing'.
HTML
<div id='cursor'>
</div>
<div class='thing' style='width:70px; height:70px; background: #fff; position: absolute; bottom: 350px; right: 800px; z-index: -1;'>
</div>
<div class='thing' style='width:70px; height:70px; background: #fff; position: absolute; bottom: 200px; right: 400px; z-index: -1;'>
</div>
JS
(function collide(){
var newInt = setInterval(function() {
function collision($cursor, $thing) {
var x1 = $cursor.offset().left;
var y1 = $cursor.offset().top;
var h1 = $cursor.outerHeight(true);
var w1 = $cursor.outerWidth(true);
var b1 = y1 + h1;
var r1 = x1 + w1;
var x2 = $thing.offset().left;
var y2 = $thing.offset().top;
var h2 = $thing.outerHeight(true);
var w2 = $thing.outerWidth(true);
var b2 = y2 + h2;
var r2 = x2 + w2;
// change 12 to alter damping higher is slower
var varies = 12;
if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2){
} else {
varies = 200;
console.log(varies);
}
$xp += (($mouseX - $xp)/varies);
$yp += (($mouseY - $yp)/varies);
$("#cursor").css({left:$xp +'px', top:$yp +'px'});
}
$(collision($('#cursor'), $('.thing')));
//$('.result').text(collision($('#cursor'), $('.thing')));
}, 20);
})();
$thing is a collection of elements, like you want, but the problem here is that you ask specific attributes from $thing like offset().left;, which can not return more than one number, therefor it just takes the first. What you should do instead is use an .each() function to loop over all the elements in $thing.
$thing.each( function( index, element ){
//your code for each thing here
});
When you are selecting element by class name(in your case using .thing) in jQuery you will get an array of elements and collision() function will take first element in an array. so to overcome this you need to uniquely select both the elements this can be done using id as a selector,You can change your code like below to work it as expected
<div id='track'>
<div class = 'container'>
<div id='cursor' class='cursor'>
</div>
<div class='thing' id="a1" style='width:70px; height:70px; background: #fff; position: absolute; bottom: 175px; right: 400px; z-index: -1;'>
</div>
<div class='thing' id="a2" style='width:70px; height:70px; background: #fff; position: absolute; bottom: 100px; right: 200px; z-index: -1;'>
</div>
</div>
</div>
(function cursorMapping(){
var $mouseX = 0, $mouseY = 0;
var $xp = 0, $yp =0;
$(document).mousemove(function(e){
$mouseX = e.pageX;
$mouseY = e.pageY;
});
function showCoords(event) {
var x = event.clientX;
var y = event.clientY;
var coor = "X: " + x + ", Y: " + y;
}
var timestamp = null;
var lastMouseX = null;
var lastMouseY = null;
var mrefreshinterval = 500; // update display every 500ms
var lastmousex=-1;
var lastmousey=-1;
var lastmousetime;
var mousetravel = 0;
var lastmousetravel = 0;
var speed;
var marker1 = 1;
var marker2 = 1;
var timer = setInterval(function(){
marker1;
marker2;
}, 20);
$(function() {
var $speedometer = $('#speed'),
_speed = 0;
$('#track').cursometer({
onUpdateSpeed: function thisSpeed(speed) {
_speed = speed;
$speedometer.text(Math.ceil(speed * 100)/100);
},
updateSpeedRate: 20
});
});
var thisInterval = setInterval(function FXInterval(){
speed = $('#speed').text();
$('#cursor').css({'background-color': '#CE7A7A'});
}, 20);
$('html').mousemove(function(e) {
var mousex = e.pageX;
var mousey = e.pageY;
if (lastmousex > -1)
mousetravel += Math.max( Math.abs(mousex-lastmousex), Math.abs(mousey-lastmousey) );
lastmousex = mousex;
lastmousey = mousey;
var speed = lastmousex + lastmousey;
setTimeout(function(){
lastmousetravel = mousetravel;
}, 20);
});
(function collide(){
var newInt = setInterval(function() {
function collision($cursor, $thing) {
var x1 = $cursor.offset().left;
var y1 = $cursor.offset().top;
var h1 = $cursor.outerHeight(true);
var w1 = $cursor.outerWidth(true);
var b1 = y1 + h1;
var r1 = x1 + w1;
var x2 = $thing.offset().left;
var y2 = $thing.offset().top;
var h2 = $thing.outerHeight(true);
var w2 = $thing.outerWidth(true);
var b2 = y2 + h2;
var r2 = x2 + w2;
// change 12 to alter damping higher is slower
var varies = 12;
if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2){
} else {
varies = 200;
console.log(varies);
}
$xp += (($mouseX - $xp)/varies);
$yp += (($mouseY - $yp)/varies);
$("#cursor").css({left:$xp +'px', top:$yp +'px'});
}
$(collision($('#cursor'), $('#a1')));
$(collision($('#cursor'), $('#a2')));
}, 20);
})();
})();

random position of images

i found a script that would position divs / images randomly. However, it isn't completely working the way i want/need it to.
The images are loaded each within a div (which isn't ideal i guess). I have around 30 images.
But they don't load nicely and var posy = (Math.random() * ($(document).height() - 0)).toFixed(); doesn't work nicely either. The images mostly load on top (i think that the images in the blog don't count so it gets the height without images?)
So what I want: Load the in more nicely Randomize them so they get to the bottom of the page, too
var circlePosition = document.getElementsByClassName('circle');
console.log(circlePosition);
function position() {
for (var i = 0; i < circlePosition.length; i++ ) {
//give circle a random position
var posx = (Math.random() * ($(document).width() - 0)).toFixed();
var posy = (Math.random() * ($(document).height() - 0)).toFixed();
//apply position to circle
$(circlePosition[i]).css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
})
}
} //end function position
var circleTotal = circlePosition.length;
$('.circle').click(function() {
$(this).fadeOut();
circleTotal = circleTotal - 1;
console.log(circleTotal);
if(circleTotal == 0) {
position()
$('.circle').fadeIn();
}
});
position();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="//placehold.it/1x5000"> <!-- Placeholder image to show issue -->
<div class="circle">
<img src="http://static.tumblr.com/tensqk8/k8anq0438/01.png">
</div>
<div class="circle">
<img src="http://static.tumblr.com/tensqk8/k8anq0438/01.png">
</div>
A clean and readable and solution without a jQuery dependence might be something like this. It avoids unnecessarily wrapping your images in divs by positioning the images themselves. It includes a hidden element as a sort of "poor man's" shadow DOM.
http://jsfiddle.net/sean9999/yv9otwr7/9/
;(function(window,document,undefined){
"use strict";
var init = function(){
var canvas = document.querySelector('#x');
var icon_template = document.querySelector('#template');
var icon_width = 40;
var icon_height = 30;
var the_images = [
'http://static.tumblr.com/tensqk8/k8anq0438/01.png',
'http://static.tumblr.com/tensqk8/rYanq05el/04.png',
'http://static.tumblr.com/tensqk8/SYknq05py/05.png',
'http://static.tumblr.com/tensqk8/s7inq057d/03.png'
];
var pickRandomImage = function(){
var i = Math.floor( Math.random() * the_images.length );
return the_images[i];
};
var total_number_of_images = 10;
var max_height = canvas.offsetHeight - icon_height;
var max_width = canvas.offsetWidth - icon_width;
var randomCoordinate = function(){
var r = [];
var x = Math.floor( Math.random() * max_width );
var y = Math.floor( Math.random() * max_height );
r = [x,y];
return r;
};
var createImage = function(){
var node = icon_template.cloneNode(true);
var xy = randomCoordinate();
node.removeAttribute('id');
node.removeAttribute('hidden');
node.style.top = xy[1] + 'px';
node.style.left = xy[0] + 'px';
node.setAttribute('src',pickRandomImage());
canvas.appendChild(node);
};
for (var i=0;i<total_number_of_images;i++){
createImage();
};
};
window.addEventListener('load',init);
})(window,document);
body {
background-color: #fed;
}
#x {
border: 3px solid gray;
background-color: white;
height: 400px;
position: relative;
}
#x .icon {
position: absolute;
z-index: 2;
}
<h1>Randomly distributed images</h1>
<div id="x"></div>
<img src="#" class="icon" hidden="hidden" id="template" />
try moving your position(); call inside the $(window).load function.
I think maybe the images are being positioned before all the images have loaded, so the page is shorter then.

Displaying Hidden Div on Canvas position mousemoves

Currently I'm creating a sheet of graph paper with the canvas object in HTML5. I'm able to create the canvas as well as fill in the selected areas with a color by finding the x/y position. Unfortunately I'm having some troubles using the jQuery mousemove method to display a pop-up of the information selected for the square.
Here's my code:
Canvas Creation/Layout:<br>
<script type="text/javascript">
var canvas;
var context;
var color;
var state;
var formElement;
var number = 0;
function showGrid()
{
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
context.lineWidth=0.5;
context.strokeStyle='#999999';
lineSpacing=10;
var xPos = 0;
var yPos = 0;
var numHorizontalLines = parseInt(canvas.height/lineSpacing);
var numVerticalLines = parseInt(canvas.width/lineSpacing);
state = new Array(numHorizontalLines);
for (var y = 0; y < numHorizontalLines; ++y)
{
state[y] = new Array(numVerticalLines);
}
for(var i=1; i<=numHorizontalLines;i++)
{
yPos=i*lineSpacing;
context.moveTo(0,yPos);
context.lineTo(canvas.width,yPos);
context.stroke;
}
for(var i=1; i<=numVerticalLines; i++)
{
xPos=i*lineSpacing;
context.moveTo(xPos,0);
context.lineTo(xPos,canvas.height);
context.stroke();
}
}
function fill(s, gx, gy)
{
context.fillStyle = s;
context.fillRect(gx * lineSpacing, gy * lineSpacing, lineSpacing, lineSpacing);
if(s != null)
{
}
}
function getPosition(e)
{
var x = new Number();
var y = new Number();
var canvas = document.getElementById("canvas");
if (e.pageX || e.pageY)
{
x = e.pageX;
y = e.pageY;
}
else
{
x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
var gx = Math.floor((x / lineSpacing));
var gy = Math.floor((y / lineSpacing));
state[gy][gx] = true;
fill(color, gx, gy);
addNumber();
}
HTML:
<div class="graphpaper" id="graphpaper" onclick="getPosition(event)" style="width:956px; height:1186px;">
<img src="images/PosterBorder_Top.png" align="right"/>
<img src="images/posterBorder_left.png" align="left" valign="top"/>
<canvas id ="canvas" width = "920" height = "1160" align="left">
</canvas>
</div>
<!-- HIDDEN / POP-UP DIV -->
<div id="pop-up">
<h3>Pop-up div Successfully Displayed</h3>
<p>
This div only appears when the trigger link is hovered over.
Otherwise it is hidden from view.
</p>
</div>
jQuery for Pop-Up display:
$('#canvas').mousemove(function(event){
console.log("Here I am!");
$('div#pop-up').show().appendTo('body');
});
Any suggestions? I'm obviously missing something but from what I've done this should work I believe.

Categories