Skip to content Skip to sidebar Skip to footer

P5js Image Array

I would like to draw a random image to the canvas every time the mouse is clicked. Console: p5.js says: image() was expecting p5.Image|p5.Element for parameter #0 (zero-based ind

Solution 1:

You need a new variable to refer to a randomly selected image from your array of three images.

Add following line to the very top of your code

var randomImageLocation

Change line

img[i] = loadImage('img/img' + i + '.png')

to

img[i] = 'img/img' + i + '.png' // store the image location in array only

then change line

let img = random('img')

to

randomImageLocation = img[Math.floor(Math.random() * img.length)]; 

then in the mouseClicked function use the randomImageLocation variable instead of img

let randomImage = loadImage(randomImageLocation)
image(randomImage,200, 200, 50, 50)

See this this question for more details on selecting a random element from an array Getting a random value from a JavaScript array


Post a Comment for "P5js Image Array"