0

so I'm making a small game on the HTML5 Canvas. I have an array of images which are displayed on the canvas, and a button (which is just an event listener checking if a certain area of the canvas is clicked.) When this button is clicked, I would like a random image to be selected so that I can have it perform a task (running a function, and an animation, which I will implement after the random selection is sorted).

I am assuming I can use some variant of math.random() to randomly select an image, but do I first need to assign each of the images to a value, e.g. if there was 5 images, 0 to 4?

Here is the array code:

        var imageArray = new Array();
        imageArray[0] = "./assets/1.png";
        imageArray[1] = "./assets/2.png";
        imageArray[2] = "./assets/3.png";
        imageArray[3] = "./assets/4.png";
        imageArray[4] = "./assets/5.png";

        var box = new Image();
        box.onload = function () {
            ctx.drawImage(box, 50, 180, 150, 133);
            ctx.drawImage(box, 220, 180, 150, 133);
            ctx.drawImage(box, 390, 180, 150, 133);
            ctx.drawImage(box, 50, 320, 150, 133);
            ctx.drawImage(box, 220, 320, 150, 133);
            ctx.drawImage(box, 390, 320, 150, 133);
            ctx.drawImage(box, 50, 460, 150, 133);
            ctx.drawImage(box, 220, 460, 150, 133);
            ctx.drawImage(box, 390, 460, 150, 133);
        };
        box.src = imageArray[4];
kelso
  • 43
  • 2
  • 7

2 Answers2

0

To get a random integer, you can do the following:

Math.floor(Math.random() * max);

Where max is maximum number you want to generate, or in your case length of array. In case where max is 4 possible outputs are 0, 1, 2, 3.

Mladen Ilić
  • 1,667
  • 1
  • 17
  • 21
0

you can try something like that :

Math.floor(Math.random()*imageArray.length)

it give you a random number between 0 and your array length

take a look at this, it can help you Generating random whole numbers in JavaScript in a specific range?

Julien Amblard
  • 121
  • 1
  • 3
  • Thanks! See how I have 9 instances of imageArray[4]? Would it be possible to have the code you just showed me pick a random value just from those 9, instead of picking randomly from the 5 unique assets loaded into the array? – kelso Mar 30 '18 at 14:31