Cycle Images on Mouse Click P5Js

var img1;

var img2;

var img3;

function preload() {

 img1 = loadImage("bckgrnd.png");

 img2 = loadImage("moon.png");

 img3 = loadImage("tuktuk2.png");

}

function setup() {

  createCanvas(windowWidth, windowHeight);/*System variable that stores the width and heigth of the window, 

  it maps to window.innerWidth and window.innerHeight*/

}

function draw() {

 //image(img1, -120, 0);

 background(img1);//set the background image

 image(img2, 700, -50, 700, 700);

 image(img3, 850, 50, 400, 500);

 

}Preformatted text

Hi, I wanted to know how to cycle through images on a mouse click event. My idea is to cycle through multiple images whenever the mouse is clicked.

Hello,

You will need to store your images in an array for this.
Once it is done, you can have a global variable holding the index of the current image.
On mouse clicked, you simply increase that index and it will change the image.

Here’s a little example:

let imgs = [];
let idx;

function setup() {
  createCanvas(windowWidth, windowHeight);
  imgs[0] = 0;
  imgs[1] = 1;
  imgs[2] = 2;
  idx = 0;
}

function draw() {
  background(20);
  fill(220);
  textSize(100);
  text(imgs[idx], windowWidth / 2, windowHeight / 2);
}

function mouseClicked() {
  idx++;
  if (idx > imgs.length - 1) {
    idx = 0;
  }
}
1 Like

Hi,
Thank you for your feedback. I am new to P5Js. I guess ‘idx’ stands for index. How do I add images to the array?

Thanks

If you need to know the basics, I recommend to watch some tutorials!

2 Likes

Thanks a lot. This works out.

1 Like