Display images randomly by clicking

Hello,

I’m trying to display images (10 or more) randomly when you click on the canvas. At the moment there is only one image displayed, and I don’t know how to proceed for the rest. Should I use img(); or createImg(); ?

Here is my code: https://editor.p5js.org/NicolasTilly/sketches/dZUpAB3rd

Thanks for your help.

1 Like

Although it’s for Processing’s Java Mode, this article about arrays is very relevant for your code: :angel:

2 Likes

I changed my code :slight_smile:

let imgs = [];
function preload() {
  for (var i = 1; i < 10; i++) {
    imgs[i] = loadImage("assets/img_" + i + ".png");
  }
}

but displaying a random image at the click doesn’t work yet.

1 Like

In function mousePressed assign a random value to index and say image(imgs[index], mouseX,mouseY);

1 Like

something like that?

function mouseClicked() {
  var index = random([0,1,2,3,4,5,6,7,8,9]);
  image(imgs[index], mouseX, mouseY, 200, 360);
}

var index=int(random(9));

1 Like

Thank you! It’s working!

The result: https://editor.p5js.org/NicolasTilly/full/dZUpAB3rd

And the code:

let imgs = [];

function preload() {
  for (var i = 0; i < 10; i++) {
    imgs[i] = loadImage("assets/img_" + i + ".png");
  }
}

function setup() {
  createCanvas(windowWidth, windowHeight);
  background(245);
  imageMode(CENTER);
}

function mouseClicked() {
  var index=int(random(9));
  image(imgs[index], mouseX, mouseY, 200, 360);
}

function draw() {
}

function keyTyped() {
  if (key === 'a') {
    clear();
  }
}
2 Likes

not sure whether image #9 appears though?

you’re right, the image #9 doesn’t appears :confused:

And it’s very strange because, the code working on the editor, but in present mode the images do not load… The error in the console: “Failed to load resource: the server responded with a status of 404 ()”

I think use random with 10 as parameter

I don’t know. Did you upload the images as ressources?