How to choose random image from image set in javascript - javascript

I have been using the following code to generate random images, but none of the pictures are showing up.
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
var theImages = new Array()
theImages[0] = '<img class="atvi-image-image" alt=""src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png" title="" height="467" width="675">'
theImages[1] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png" title="" height="732" width="1084">'
theImages[2] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-extra-slots.png" title="" height="480" width="752">'
theImages[3] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-2025.png" title="" height="412" width="683">'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write(theImages[whichImage]);
}
</script>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
showImage();
</script>
</body>
</html>
Thank you in advance for your help!

You already have the full <img> tag in the array. So just use:
document.write(theImages[whichImage]);
Although I would advise against using document.write. Of course, in your situation, where it's being executed in the middle of HTML, I don't see much of a problem. It would be bad if document.write were executed after the page was rendered. Normally, the preferred method is something like the appendChild method or even setting innerHTML, although it would take some refactoring to get your code to use them.
Here's an example of how I'd set it up:
(function () {
var theImages = [{
src: "http://www.techinasia.com/techinasia/wp-content/uploads/2009/12/smile.png",
width: "675",
height: "467"
}, {
src: "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQdcHlJqgIKNOS0DaEjO31xK1zYtmJlza8z70ljiKFbo2ZgLdh9eA",
width: "1084",
height: "732"
}, {
src: "http://cdn2-b.examiner.com/sites/default/files/styles/large_lightbox/hash/68/d1/68d11ab242d40c8d5abbe8edb58fd4ed_0.jpg?itok=M3qtK47_",
width: "200",
height: "200"
}];
var preBuffer = [];
for (var i = 0, j = theImages.length; i < j; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = theImages[i].src;
preBuffer[i].width = theImages[i].width;
preBuffer[i].height = theImages[i].height;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
window.getRandomImage = function () {
var whichImage = getRandomInt(0, preBuffer.length - 1);
return preBuffer[whichImage];
}
})();
window.onload = function () {
var newImage = getRandomImage();
console.log(newImage);
document.body.appendChild(newImage);
};
DEMO: http://jsfiddle.net/wFjGv/
This code uses a new object to hold the details for each image. That way, you can easily set and get each image's properties that you need without hardcoding HTML.
It preloads the images in the preBuffer array, and when needed, an image is retrieved from the array, and put into the <body>. You can change its target in the onload event. The getRandomImage function returns a random image from that array. I updated the method of getting a random integer as well.

You are setting an <img src= something that is not what you want. Your array (theImages) is storing full <img> tags, not just the link to that image.
Either change you theImages array to store values like so:
theImages[0] = "/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png"
OR use the current setup as the image tag.
document.write(theImages[whichImage]);
Also:
With random numbers, you should probably stick to Math.floor() lest
you round over your max length.
var j = 0 is missing a ;
theImages img tags are not closed (<img ... />

Try this-
var srcs = [
"/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png",
"/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png",
"foo/bar.jpg"
], imgs = [];
function init() {
"use strict";
var i, x, div;
div = document.createElement('div');
div.id = 'imageContainer';
document.querySelector('body').appendChild(div);
for (i = 0; i < srcs.length; i += 1) {
x = new Image();
x.src = srcs[i];
imgs.push(x);
}
}
function showRandom() {
"use strict";
document.querySelector('#imageContainer').innerHTML = imgs[Math.random * imgs.length];
}
init();
To add a random image-
showRandom();
PS - You shouldn't use document.write, but if you do, you should close the stream by document.close, to tell the browser to finish loading the page. Read more - MDN JS Docs

Related

How to make images appear randomly in Javascript?

I need to create a web page with a button that says "start game". When this button is clicked, 5 images I have downloaded (img1.png...img5.png) must appear randomly, one at a time, every half a second. Here is my code so far, any help would be greatly appreciated!
<html>
<head>
<script>
var rollImagesSchedule;
var rollImagesCounter;
function rollImagesAnimation(){
rollImagesCounter = 0;
rollImagesSchedule = setInterval(500);
}
function rollImages(){
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
rollImagesCounter = rollImagesCounter + 1;
if (rollImagesCounter == 10){
clearInterval(rollImagesSchedule);
}
}
</script>
</head>
<body>
<h1>Game</h1>
<button onClick="rollImagesAnimation()">Start frog game</button>
<br /><br />
<img id="display" style='width:200px; height:200px;'>
</body>
</html>
I think you're getting stuck with the way to use setInterval.
You can try to create a counter outside setInterval function, and nest all of your works inside of it. And the counter should be checked at the top.
function rollImages(){
var counter = 0;
var interval = setInterval(function () {
if (counter === 10) {
clearInterval(interval);
return;
}
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
counter++;
}, 500);
}
Then, you can edit the way to catch event rollImages:
<button onClick="rollImages()">Start frog game</button>
My English is not very good, so I might misunderstand your question. Let me answer it according to what I understand.
Your requirement is to randomly display one of the five pictures every 500 milliseconds, right? If so, you can try this idea:
Put the src of 5 pictures into an array
var imageSrcs = ["image1","image2","image3","image4","image5"];
Every 500 milliseconds, execute the following function:
function rollImages(){
// Randomly generate a random number between 0-4
int index = Math.floor(Math.random() * 5) + 1;
var theImage = document.getElementById("display");
// Use random numbers as subscripts and take values from the array
theImage.src = imageSrcs[index];
}
You can store the images name files into an array and then setInterval a random number and assign the source of an img html element:
var list = [
"image1.jpg",
"image2.jpg",
"image3.jpg",
];
var i = 0;
function changeImgs() {
var imageValue = Math.floor(Math.random() * list.length - 1) + 1;
image.src = list[imageValue];
}
setInterval(function() {
changeImgs()
}, 2000);
window.onload = changeImgs;
<img id="image" class="size">

JavaScript Image Swap with a Timer and Fade

I have a unique situation where I am trying to take an image and swap it out after a specific time. I have that part working however I also need the pictures to fade in and out of each other and I can not figure that part out. Please help if you can.
JavaScript:
<script type="text/javascript">
var picPaths = ['images/Front1.jpg','images/Front2.jpg','images/Front3.jpg'];
var curPic = -1;
var imgO = new Array();
for(i=0; i < picPaths.length; i++) {
imgO[i] = new Image();
imgO[i].src = picPaths[i];
}
function swapImage() {
curPic = (++curPic > picPaths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
setTimeout(swapImage,5000);
}
window.onload=function() {
imgCont = document.getElementById('imgBanner');
swapImage();
}
</script>
HTML:
div img id="imgBanner" src="" alt="" / /div
I have the correct <> in places on the HTML however it would not let me post the HTML into the screen.

Different intervals between images

I am studying for GCSE computing and need to be able to change the interval between different images. My code at the moment looks something like this...
<!DOCTYPE html>
<html>
<body>
<h1> Traffic lights can change on their own </h1>
<img src="RED.jpg" id= "traffic" width="155" height="198">
<script>
var myImage = document.getElementById("traffic");
var imageArray = ["RED.jpg", "RED-ORANGE.jpg", "GREEN.jpg", "ORANGE.jpg"];
var imageIndex = 0;
function changeImage()
{
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setInterval(changeImage,1000);
</script>
</body>
</html>+
If you could include some of this code whilst changing the intervals that would be ideal.
Supposing you want to solve this using Javascript only:
Source documentation
// Save the var timeoutID = window.setTimeout(code, [delay]);
var imageTimers = [500, 1000, 2000, 4000];
var timeTochange = Math.random() * 3000; // or whatever you want to use...
var aTimer = setTimeout(changeImage, timeTochange);
// On the changeImage, alter the timeTochange var.
function changeImage() {
// ...stuffs...
clearTimeout(aTimer);
timeTochange = imageTimers[imageIndex];
aTimer = setTimeout(changeImage, timeTochange);
}

how to load multiple image one by one on canvas? using loop

var ImgCanvas = new fabric.Canvas("mycanvas");
var json = {};
var IdStore = [];
var retval = [];
var retvalsrc = [];
function sava(){
//push to array for loop
$('.Jicon').each(function(){
retval.push($(this).attr('id'));
retvalsrc.push($(this).attr('src'));
})
var className = $(".Jicon");
var classnameCount = className.length;
//loop classname
for(var d = 0; d < classnameCount; d++){
updateCanvas(retval[d], retvalsrc[d]);
}
}
//change main image
function updateCanvas(_id, _src)
{
ImgCanvas.clear();
// var oImg = new fabric.Image(_src, {
fabric.Image.fromURL(_src, function(oImg) {
oImg.setWidth(500);
oImg.setHeight(400);
oImg.left = ((ImgCanvas.width/2)-(oImg.width/2));
oImg.top = 50;
oImg.selectable = false;
ImgCanvas.add(oImg);
ImgCanvas.renderAll();
});
}
i have a mutiplete Image which i wanna to load them to canvas one by one using loop , how do i achieve that ? so when i press sava the image will show one by one on the canvas.i tried to use for but it load all those image together.
can anyone give me a help here~ thank apreciate.
Demo
Let the end of the imageFromURL call the next load, and refactor the code for use a settimeout, otherwise everything will be very fast.
The images before appeared all togheter because the load is async. So with the for loop you were
rapidly starting the loading in sequence of 4 images
immediately clear 4 times a canvas that is still empty
every image will then finish loading and appear on the canvas on random order.
var ImgCanvas = new fabric.Canvas("mycanvas");
var json = {};
var IdStore = [];
var retval = [];
var retvalsrc = [];
function sava(){
$('.Jicon').each(function(){
retval.push($(this).attr('id'));
retvalsrc.push($(this).attr('src'));
})
updateCanvas();
}
//change main image
function updateCanvas() {
ImgCanvas.clear();
var _src = retvalsrc.pop();
fabric.Image.fromURL(_src, function(oImg) {
oImg.setWidth(500);
oImg.setHeight(400);
oImg.left = ((ImgCanvas.width/2)-(oImg.width/2));
oImg.top = 50;
oImg.selectable = false;
ImgCanvas.add(oImg);
ImgCanvas.renderAll();
if (retvalsrc.length > 0) {
setTimeout(updateCanvas, 1000);
}
});
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div>
<img name="001.png" class="Jicon" id="displayImage1" src="http://i795.photobucket.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/077.png" onclick="updateCanvas(this.src);">
<img name="002.png" class="Jicon" id="displayImag2" src="http://i795.photobucket.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/076.png" onclick="updateCanvas(this.src);">
<img name="003.png" class="Jicon" id="displayImage3" src="http://rs795.pbsrc.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/071.png~c100" onclick="updateCanvas(this.src);">
<img name="004.png" class="Jicon" id="displayImag4" src="http://rs795.pbsrc.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/072.png~c100" onclick="updateCanvas(this.src);">
</div>
<button onclick="sava();">sava</button>
<div id="warpper">
<canvas id="mycanvas" width="380" height="500" style="border:1px solid #000;"></canvas>
</div><!-- end of div -->
</body>

How can I make 6 images play as a gif with an on click button (Can't find whats missing in my code)

So I'm trying to get an 6 images to play (runner0 - runner5) and then go back to the beginning and so far only the first image and second image appears but the rest aren't playing but are in the same folder. I was told to use getElementById(), getElementsByName(), or getElementsByTagName(). But how would i implement those?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Project 10 11 Sample</title>
<script type="text/javascript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
var curPennant = 1;
var begin;
pennant1 = new Image();
pennant1.src = "runner0.jpg";
pennant2 = new Image();
pennant2.src = "runner1.jpg";
pennant3 = new Image();
pennant3.src = "runner2.jpg";
pennant4 = new Image();
pennant4.src = "runner3.jpg";
pennant5 = new Image();
pennant5.src = "runner4.jpg";
pennant6 = new Image();
Pennant6.src = "runner5.jpg";
function wave() {
if (curPennant == 1) {
document.images[0].src = pennant2.src;
curPennant = 2;
}
else {
document.images[0].src = pennant1.src;
curPennant = 1;
}
}
function startWaving() {
if (begin)
clearInterval(begin);
begin = setInterval("wave()",500);
}
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</script>
</head>
<body>
<p>
<img alt="" height="132" src="runner0.jpg" width="107" /></p>
<p><input type="button" value=" Wave"
onclick="startWaving();" /><input type="button" name="stop"
value=" Stop" onclick="clearInterval(begin);" /></p>
</body>
</html>
The easiest way would be to use an array and loop through it. First instantiate an array and add all your images to it, which is very easy because you named them with same names and ascending numbers.
So instead of:
var curPennant = 1;
pennant1 = new Image();
pennant1.src = "runner0.jpg";
pennant2 = new Image();
pennant2.src = "runner1.jpg";
pennant3 = new Image();
pennant3.src = "runner2.jpg";
pennant4 = new Image();
pennant4.src = "runner3.jpg";
pennant5 = new Image();
pennant5.src = "runner4.jpg";
pennant6 = new Image();
Pennant6.src = "runner5.jpg";
say:
var current = 0;
var imageArray = [];
for(i = 0; i < 6; i++){
var img = new Image();
img.src = "runner"+i+".jpg";
imageArray.push(img);
}
and in your function wave use:
function wave(){
document.images[0].src = imageArray[current++%imageArray.length].src;
}
If you just need the source names and don't need the Images (pennant1 and so on) for anything else, you could even simplify it more:
var current = 0;
var imageArray = [];
for(i = 0; i < 6; i++){
imageArray.push("runner"+i+".jpg");
}
and
function wave(){
document.images[0].src = imageArray[current++%imageArray.length];
}
NOTE: You also set the interval with:
begin = setInterval(wave, 500);
working fiddle (i just set the file name as content of a paragraph, instead you need to assign it as the source of your image)

Categories