p5js Image Array

拈花ヽ惹草 提交于 2021-01-29 10:28:55

问题


I would like to draw a random image to the canvas every time the mouse is clicked.

let img = []

function preload(){

  for (let i = 0; i < 3; i++) {
    img[i] = loadImage('img/img' + i + '.png')
  }
  
}

function setup() {
  createCanvas(windowWidth, windowHeight)
  background(200, 255,255 )
  let img = random('img')  
  
}
 
function draw() {

}

function mouseClicked() {
  image(img,200, 200, 50, 50)
  
}
<html>
<head>
  <meta charset="UTF-8">
  <script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
  <script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.dom.min.js"></script>
  <script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.sound.js"></script>
  <script language="javascript" type="text/javascript" src="sketch.js"></script>
</head>

<body>
  

</body>

</html>

Console: p5.js says: image() was expecting p5.Image|p5.Element for parameter #0 (zero-based index), received array instead.

No image appears and that error keeps popping up.

I have been looking at this similar question but can't seem to figure it out in my own issues above: stack question. As well as a coding train vid and the p5 examples.


回答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



来源:https://stackoverflow.com/questions/51233447/p5js-image-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!