mercredi 28 mars 2018

Picking a random item from an array?

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




Aucun commentaire:

Enregistrer un commentaire