Glorpy
Glorpy

Reputation: 83

Random image generation in Javascript

I have a problem that I have been trying to figure out and I can't seem to find it online. I am new to Javascript and I really want to get the hang of it. Here is my problem.

I want to be able to have an image on the screen. And when the program starts a random image is chosen from a set of images. For example. Lets say I have a green button, a blue button, and a red button. When the browser loads I want the button to be displayed at random from that set of images. Here is what I have so far, bear with me here I am still learning. Now from what I understand I have the image already there. And I am using document.getElementById to get the element of the tag right? I also have the random method to pick a number between 1 and 3. Now I just have to figure out how to make it pick between the other 2 images (blue button, and green button)

Thanks for your time.

EDIT: I'd like to be able to do this without the use of arrays or objects.

<body>
  <img src="red.jpg" id="numberOne">
</body>

<script>
  var randomNumberOne = Math.ceil(Math.random() * 3);
  var numberOne = document.getElementById("numberOne");
</script >

Upvotes: 0

Views: 1761

Answers (3)

GitaarLAB
GitaarLAB

Reputation: 14655

Without array (and no 'cheating' by using more convenient filenames):

function rand_button(){
  switch(Math.random()*3|0){
      case 0:
          return 'red.jpg';
      case 1:
          return 'blue.jpg';
      case 2:
          return 'green.jpg';
  } 
}
document.getElementById('numberOne').src=rand_button();

Note: Math.random() returns a number between 0 (inclusive) and 1 (exclusive).
For example, Math.random()*5 will never return 5.
Also good to keep in mind, you'd need to round the number (which you did). A simple trick in javasript is to use bitwise OR aka |. This will round numbers (to (2pow31)-1===2147483647 aka 31 bits) down to the nearest integer.
Thus Math.random()*3|0 can give 0, 1 and 2 (you specified 3 images).

Next I used a function that contains a switch-statement. We feed the random integer to the statement and compare each case. So if the case (random number) is 0, we return the string 'red.jpg' (etc). We use an (early) return because otherwise we'd need to break the statements (because switch-statements 'fall through' which means they are a sort of 'goto and continue from there' and it saves us from an extra var and some useless characters).

Now we simply execute () this function called rand_button to get our random string (which, in this case is the filename from the image) and set that as the source of image numberOne.

Edit:
Now, let's compare with if:

function rand_button(){
  var rnd=Math.random()*3|0;
  if(rnd===0) return 'red.jpg';
  if(rnd===1) return 'blue.jpg';
  if(rnd===2) return 'green.jpg';
}

Again, we used an 'early' return (that returns our random string, aka the file-name).
In javascript we use a strictly equal (which we write as ===) to compare such cases.
Thus if a generated random number (referenced via identifier rnd) equals a given number, we return the corresponding string.

Let's go crazy using 'short circuiting':

var rnd=Math.random()*3|0;
var elm=document.getElementById('numberOne');
elm.src= (rnd===0 && 'red.jpg') || (rnd===1 && 'blue.jpg') || (rnd===2 && 'green.jpg');

In javascript 'short circuiting' relies on statements returning a value. We combine that with javascript's idea of true/false and logical operators.
&& means 'AND', and || means 'OR'.
Now consider this example: 2===3 && 2===2
javascript will never test 2===2 because 2===3 already failed and we wanted both to be true..
On the other hand, if we used: 2===3 || 2===2, then javascript would test 2===2 because the first test 2===3 had failed.
Now the trick is.. javascript considers a non-empty string to be boolean 'true'..

SO: if our rnd number was 1, then this is a simplified explanation of what javascript 'thinks'/does:

rnd===0       // nope, so skip 'red.jpg' (that makes the contents between first `()` false)          
rnd===1       // yes           
'blue'        // that is a string (that makes the contents between second `()` true)
//hey we found a true, so we don't care about the final OR (`|| (rnd===2 && 'green.jpg')`)           
//so let's return true value: 'blue.jpg'

(I'm not going into ternary here, because then we also get the problem of what do do with the last 'else'-case. If we needed a default inside our switch or else statement, then the ternary would have been relevant to).

That's why the array-solution:

document.getElementById('numberOne').src= ['red.jpg','blue.jpg','green.jpg'][Math.random()*3|0];

is the simplest/shortest solution (since you don't reuse it: you only use it once on page-load).

Bonus:
You could use a function to get you a random string from an array (that you pass as argument).

function get_rnd_str(arr){
  return arr[Math.random()*arr.length|0];
}
var elm=document.getElementById('numberOne');
elm.src=get_rnd_str(['red.jpg','blue.jpg','green.jpg']);

Again, using what is explained above: we let javascript tell us length of the array and use that number as our multiplier to calculate our random number.
The obvious advantage is that we no longer need to hard-code our multiplier: it will always give a valid number (as in an index to our array that actually (should) hold a value).
Now we simply pass the function an array of consecutive strings and the function returns us a random result.

Upvotes: 3

ianaya89
ianaya89

Reputation: 4243

You can have an array with the images and then access an image using the random number as index.

Example:

var images ['image1.jpg','image3.jpg','image3.jpg'];

var image = images[Math.ceil(Math.random() * 3)];

This is another dirty solution without using arrays and objects:

If your images names are not important, you can name your images as 'button1.jpg', 'button2.jpg', 'button3.jpg' ...

Then you only need to wrap the random number among 'button' and '.jpg'

var image = 'button' + Math.ceil(Math.random() * 3) + '.jpg';

Upvotes: 3

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try this

With list :

var list=["img1.jpg","img2.jpg","img3.jpg"];
var randomNumberOne = Math.ceil(Math.random() * 3);
var img = document.getElementById("numberOne"); 
img.src=list[randomNumberOne];

If you have images like 1.jpg or 2.jpg in your root folder you don't have to use any array

Then Try this

var randomNumberOne = Math.ceil(Math.random() * 3);
var img = document.getElementById("numberOne"); 
img.src=randomNumberOne + ".jpg" // Change the type whatever it is

Upvotes: 1

Related Questions