问题描述
每次单击鼠标时,我想在画布上随机绘制一个图像.
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,而是接收数组.
没有图像出现,错误不断弹出.
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 图像数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!