Get random images when clicking on image for javascript - javascript

I am currently learning Javascript, and I was able to create a simple game where the shapes and color will change and it will move around. I am stuck on how to input images...please help me!! =( Thank you! =)
This is the site to the game I created http://sites.codeschool.org.uk/?site=imat3ap0t
I want to change the shapes to 3 jpg pictures I have and have it do the same thing. I am so stuck!
function getRandomColor() {
var letters = '0123456789ABCDEF'.split(''); //the numbers&letters are for color codes. split is the string (set of numbers and letters into an array)
var color = '#'; //color codes start with #
for (var i = 0; i < 6; i++) {
color += letters[Math.round(Math.random() * 16)];
}
return color;
}
var clickedTime;
var createdTime;
var reactionTime;
function makeBox() {
var time = Math.random();
time = time * 5000;
setTimeout(function () {
if (Math.random() > 0.5) {
document.getElementById("box").style.borderRadius = "100px";
} else {
document.getElementById("box").style.borderRadius = "0";
}
var top = Math.random();
top = top * 300;
var left = Math.random();
left = left * 500;
document.getElementById("box").style.top = top + "px";
document.getElementById("box").style.left = left + "px";
document.getElementById("box").style.backgroundColor = getRandomColor();
document.getElementById("box").style.display = "block";
createdTime = Date.now();
}, time);
}
document.getElementById("box").onclick = function () {
clickedTime = Date.now();
reactionTime = (clickedTime - createdTime) / 1000;
document.getElementById("time").innerHTML = reactionTime;
document.getElementById("box").style.display = "none";
makeBox();
}
makeBox();
Thank you guys for the response!

Well you will need to modify your function to something like this:
function getRandomImage() {
// All of the image options
// This is very similar to string of characters you have now
var images = ['path/to/image/1', 'path/to/image/2', 'path/to/image/3']
// Randomly select one image path
// By using images.length we don't have to hardcode the length like the "16" you're using, which is good incase the list changes
var imagePath = images[Math.floor(Math.random() * images.length)];
// Return random image path
return imagePath;
}
Then you will probably want an img tag somewhere in your document, instead of the div you are using now:
<img id="changing-image"></img>
Then you can use more javascript to find the image and change its src property:
var image = document.getElementById("changing-image");
image.src = getRandomImage();

Related

How do I remove setInterval from progress bar in Javascript and make appear the VerticalBar instantaneously?

I have the classical Progress bar in Javascript. I Would like to simply place the vertical bar without seeing it moving on the screen.
function progressbar() {
var vertical_bar2 = document.querySelector("#P5 .vl5");
var element = document.getElementById("myprogressBar");
var ValueSet = 25
var width = 0;
document.getElementById("vl5").style.display='';
document.getElementById("value2").style.display='';
document.getElementById("value1").style.display='';
var identity = setInterval(scene, 10);
function scene() {
if (width >= ValueSet) {
clearInterval(identity);
} else {
width++;
vertical_bar2.style.left = `${width}%`;
document.getElementById("value2").innerHTML = ValueSet
}
}
}
I am trying the following script but it is not working
function progressbar() {
var vertical_bar2 = document.querySelector("#P5 .vl5");
var element = document.getElementById("progressBar");
var CE = 25
var width = 0;
document.getElementById("vl5").style.display='';
document.getElementById("Value2").style.display='';
document.getElementById("Value1").style.display='';
vertical_bar2.style.left = 25;
document.getElementById("Value").innerHTML = CE
}
Based on the code your provided, it looks like you just need to set a unit for the left property of your bar. Currently you are only setting a value (25), but without a unit (%, px, em, etc.) it will not apply anything.
vertical_bar2.style.left = "25%";
or
vertical_bar2.style.left = `${CE}%`;

Prevent double images in function using Math.random

I have a function that adds random images to my divs that disappear over time and create a mouse trail. My issue is: there are double images.
I'd like to add something that checks if the background url is already located on the page and if that's the case, skips to the next in the array and check it again until until it comes across one that is not there. So like a loop that refreshes every time a 'trail' is being created.
Maybe I am asking for something that won't work? What if all the images are already on the page? I don't really have an answer for it and I also don't have an idea how to solve that problem yet.
For now I tried adding a counter that checks the usedImages and counts them, but it seems to have flaws and I am unsure where to look or how to fix it. Does anyone have any tips on how to do this? Is it even possible?
My fiddle
var bgImages = new Array(
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/schraegluftbild-1024x725.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/pikto-608x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhausen-EG-Grundriss-913x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/lageplan-945x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhausen-EG-Grundriss-913x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhauser-Esch-Modell-2-1024x768.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/07/DSCN3481-1024x768.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/07/zoom-in-3_ASTOC-1024x683.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2016/07/IMG_1345-1024x768.jpg"
);
const numberOfImages = 10;
const timesPerSecond = .1;
var usedImages = {};
var usedImagesCount = 0;
function preloadImages(images) {
for (i = 0; i < images.length; i++) {
let l = document.createElement('link')
l.rel = 'preload'
l.as = 'image'
l.href = images[i]
document.head.appendChild(l);
}
}
function animate(e) {
var image = document.createElement('div');
image.classList.add('trail');
var sizew = 200;
var sizeh = 200;
image.style.transition = '3s ease';
image.style.position = 'fixed';
image.style.top = e.pageY - sizeh / 2 + 'px';
image.style.left = e.pageX - sizew / 2 + 'px';
image.style.width = sizew + 'px';
image.style.height = sizeh + 'px';
var random = Math.floor(Math.random() * (bgImages.length));
if (!usedImages[random]) {
image.style.backgroundImage = "url(" + bgImages[random] + ")";
usedImages[random] = true;
usedImagesCount++;
if (usedImagesCount === bgImages.length) {
usedImagesCount = 0;
usedImages = {};
}
} else {
animate(e);
}
console.log(usedImages);
console.log(usedImagesCount);
image.style.backgroundSize = 'cover';
image.style.pointerEvents = 'none';
image.style.zIndex = 1;
document.body.appendChild(image);
//opacity and blur animations
window.setTimeout(function() {
image.style.opacity = 0;
image.style.filter = 'blur(20px)';
}, 40);
window.setTimeout(function() {
document.body.removeChild(image);
}, 2100);
};
window.onload = function() {
preloadImages(bgImages);
var wait = false;
window.addEventListener('mousemove', function(e) {
if (!wait) {
wait = true;
setTimeout(() => {
wait = false
}, timesPerSecond * 800);
animate(e);
}
});
};

JS - How to change image SRC with separate variable?

How do you change an image path with a separate variable in JavaScript? Here's an example of what I mean:
function changeImage() {
var newName = "image1";
var imageID = document.getElementById("imageID");
imageID.src = "images/" + newName + ".png";
}
The code I'm actually using is something like this (only the relevant pieces, though):
var choices5 = ["Rock", "Scissors", "Lizard", "Paper", "Spock"];
function RPS5() {
var aiChoiceNumber = Math.floor(aiNumberDecider * 5);
var aiChoice = choices5[aiChoiceNumber];
var userchoiceNumber;
var userChoice = this.value;
for (var i = 0; i < choices5.length; i++) {
if (userChoice == choices5[i])
userchoiceNumber = i;
}
RPS(userchoiceNumber, aiChoiceNumber, choices5, outcomes5);
userImage.src = "images/" + userChoice + ".png";
console.log(userChoice + ", " + aiChoice);
}
In case you haven't figured it out yet, I'm making a web-based RPSLS game. The pictures in the directory that I'm trying to reach are there, but they don't change when I click the button to play the game / change my choice.
Thanks to everyone in advance!
I threw together a quick plunk that picks random images, in case looking at this code might help as a follow-on to our previous discussion: http://plnkr.co/edit/BfFqel0sBnI68vNejUSr?p=preview
function init() {
var images = [
'https://www.bryanrock.com/application/files/7914/3349/4593/rock.png',
'https://images-na.ssl-images-amazon.com/images/I/81tAWzf0iKL._SY450_.jpg',
'https://cdn1.creativememories.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/s/c/scissors1.jpg',
'http://animals.net/wp-content/uploads/2017/02/Lizard-2-640x425.jpg',
'http://www.tabletmag.com/wp-content/files_mf/spock62037.jpg'
];
var image = document.getElementById('image');
setInterval(function() {
var rnd = Math.floor(Math.random() * 5);
image.src = images[rnd];
image.onload = function() {
var nw = image.naturalWidth;
var nh = image.naturalHeight;
if (nw > nh) {
image.width = 300;
image.height = 300 * nh / nw;
}
else {
image.height = 300;
image.width = 300 * nw / nh;
}
};
}, 1000);
}

Move text up with javascript

So I need function like this one, -link- but just to move text up, not left. How to achieve this?
So, this is code that moves text left:
//Text fade
var bgcolor;
var fcolor;
var heading;
//Number of steps to fade
var steps;
var colors;
var color = 0;
var step = 1;
var interval1;
var interval2;
//fade: fader function
// Fade from backcolor to forecolor in specified number of steps
function fade(headingtext,backcolor,forecolor,numsteps) {
if (color == 0) {
steps = numsteps;
heading = "<font color='{COLOR}'>"+headingtext+"</strong></font>";
bgcolor = backcolor;
fcolor = forecolor;
colors = new Array(steps);
getFadeColors(bgcolor,fcolor,colors);
}
// insert fader color into message
var text_out = heading.replace("{COLOR}", colors[color]);
// write the message to the document
document.getElementById("fader").innerHTML = text_out;
// select next fader color
color += step;
if (color >= steps) clearInterval(interval1);
}
//getFadeColors: fills colors, using predefined Array, with color hex strings fading from ColorA to ColorB
//Note: Colors.length equals the number of steps to fade
function getFadeColors(ColorA, ColorB, Colors) {
len = Colors.length;
//Strip '#' from colors if present
if (ColorA.charAt(0)=='#') ColorA = ColorA.substring(1);
if (ColorB.charAt(0)=='#') ColorB = ColorB.substring(1);
//Substract red green and blue components from hex string
var r = HexToInt(ColorA.substring(0,2));
var g = HexToInt(ColorA.substring(2,4));
var b = HexToInt(ColorA.substring(4,6));
var r2 = HexToInt(ColorB.substring(0,2));
var g2 = HexToInt(ColorB.substring(2,4));
var b2 = HexToInt(ColorB.substring(4,6));
// calculate size of step for each color component
var rStep = Math.round((r2 - r) / len);
var gStep = Math.round((g2 - g) / len);
var bStep = Math.round((b2 - b) / len);
// fill Colors array with fader colors
for (i = 0; i < len-1; i++) {
Colors[i] = "#" + IntToHex(r) + IntToHex(g) + IntToHex(b);
r += rStep;
g += gStep;
b += bStep;
}
Colors[len-1] = ColorB; // make sure we finish exactly at ColorB
}
//IntToHex: converts integers between 0 - 255 into a two digit hex string.
function IntToHex(n) {
var result = n.toString(16);
if (result.length==1) result = "0"+result;
return result;
}
//HexToInt: converts two digit hex strings into integer.
function HexToInt(hex) {
return parseInt(hex, 16);
}
var startwidth = 0;
//scroll: Make the text scroll using the marginLeft element of the div container
function scroll(startw) {
if (startwidth == 0) {
startwidth=startw;
}
document.getElementById("fader").style.marginLeft = startwidth + "px";
if (startwidth > 1) {
startwidth -= 1;
} else {
clearInterval(interval2);
}
}
function fadeandscroll(txt,color1,color2,numsteps,fademilli,containerwidth,scrollmilli) {
interval1 = setInterval("fade('"+txt+"','"+color1+"','"+color2+"',"+numsteps+")",fademilli);
interval2 = setInterval("scroll("+containerwidth+")",scrollmilli);
}
Something like this seems to do what you want, but jQuery would have been easier.
Demo: Vertical Marquee Demo
window.document.addEventListener("DOMContentLoaded", function()
{
var elm = window.document.querySelectorAll("#display span")[0], height = elm.parentNode.offsetHeight;
elm.style.position = "relative";
elm.style.top = "0px";
var timer = setInterval(function()
{
var top = Number(elm.style.top.replace(/[^\d\-]/g, ''));
top = top > -height ? top - 1 : height;
elm.style.top = top + "px";
}, 50);
/*
* If you want to stop scrolling, call clearInterval(timer);
*
* Example set to stop when clicked.
*/
elm.addEventListener("click", function()
{
clearInterval(timer);
}, false);
}, false);

Particles with CSS and JavaScript

I'm trying to create something like a very simple particle system. No physics required at this point, just divs that are animated to look like bubbles, or bees, or whatever. The code below creates the divs and through CSS I can make them change position, floating upwards. But I can't seem to workout how to destroy particles. Each particle does it's motion and then returns back to it's original point. I would prefer if it was removed completely.
Thank you.
/* ==================== PARTICLES CONTROLLER ==================== */
/**
* Particle controller interates through all elements with
* CSS class name PARTICLE_CSS and when found a ParticleController is instantiated
* for each of the elements.
*/
function ParticleBaseController(){
var ParticleContainer = document.querySelectorAll(PARTICLE_CSS),
ParticleContainerLength = ParticleContainer.length;
for (var i = ParticleContainerLength - 1; i >= 0; i--){
new ParticleController(ParticleContainer[i]);
};
};
function ParticleController(element) {
var particleElement, fragment = document.createDocumentFragment();
var numberOfParticles = 1;
for (var i = 0; i < numberOfParticles; i ++) {
particleElement = document.createElement("div");
particleElement.addClassName(PARTICLE_ELEMENT_CSS_CLASS);
var Ypos = Math.floor((Math.random()*200)+1);
var Xpos = Math.floor((Math.random()*200)+1);
particleElement.style.top = Ypos + "px";
particleElement.style.left = Xpos + "px";
fragment.appendChild(particleElement);
}
element.appendChild(fragment);
setTimeout(ParticleBaseController, 3000);
};
This worked for me. I am guessing that the way it works is that particles are only appended to the container as long as there are fewer than 15. Although I do not know how they are actually destroyed. But on screen I can only ever see 15 particles at a time, or however many I set then number to.
/* ==================== PARTICLES CONTROLLER ==================== */
const NumberOfParticles = 15;
function smoking()
{
var container = document.getElementById('particleContainer');
for (var i = 0; i < NumberOfParticles; i++)
{
container.appendChild(createParticle());
}
}
function randomFloat(low, high)
{
return low + Math.random() * (high - low);
}
function createParticle()
{
var particleDiv = document.createElement('div');
particleDiv.style.top = "-300px";
particleDiv.style.left = "200px"
particleDiv.style.webkitAnimationName = 'smoke-rise, smoke-fade';
var SmokeDuration = randomFloat(5, 10)+"s";
var FadeDuration = randomFloat(4, 11)+"s";
var SmokeDelay = randomFloat(0, 5)+"s";
var FadeDelay = randomFloat(2, 9)+"s";
particleDiv.style.webkitAnimationDuration = SmokeDuration + ', ' + FadeDuration;
particleDiv.style.webkitAnimationDelay = SmokeDelay + ', ' + FadeDelay;
return particleDiv;
}
window.addEventListener("DOMContentLoaded", smoking, false);

Categories