p5js 图像数组 [英] p5js Image Array

查看:30
本文介绍了p5js 图像数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次单击鼠标时,我想在画布上随机绘制一个图像.

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>

控制台: p5.js 说:image() 期望参数 #0(从零开始的索引)的 p5.Image|p5.Element,而是接收数组.

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.

我一直在看这个类似的问题,但似乎无法在我上面的问题中弄清楚:堆栈问题.以及编码训练 vid 和 p5 示例.

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.

推荐答案

您需要一个新变量来引用从三张图片组成的数组中随机选择的一张图片.

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

换行

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

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

然后换行

let img = random('img')

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

然后在 mouseClicked 函数中使用 randomImageLocation 变量代替 img

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

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

有关从数组中选择随机元素的更多详细信息,请参阅此问题 从 JavaScript 数组中获取随机值

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

这篇关于p5js 图像数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆