图像数组p5.js [英] Image array p5.js
问题描述
我已经创建了一些嵌套数组来显示图像数组,我无法理解的一件事是它重复了相同的图像,而不是在每个循环中都绘制一个新的图像.
I've created some nested arrays to display array of Images, one thing I cant get right it repeats the same image instead of drawing a new one in every loop.
这是我的示例代码模拟我的问题
here is my example code simulates my problem
var images = [];
function preload() {
for (var i = 0; i< 3; i++) {
images[i] = loadImage("img/img" + i + ".jpg");
}
}
function setup() {
createCanvas(900, 900);
background(0);
preload();
}
function draw() {
//image(images[0],0,0);
for ( var y= 0; y < height; y=y+300) {
for ( var x =0; x < width; x=x+300) {
for ( var z = 0; z < 3; z++) {
image(images[z], x, y );
}
}
}
}
作为图像,我只是使用其中的300x300 jpgs 3张进行了测试.
as images, i just used 300x300 jpgs 3 of them to test out.
推荐答案
我可能是错的,但是快速阅读您的代码,看起来您正在相互绘制3张图像:
I might be wrong, but quickly reading through your code, it looks you're drawing 3 images on top of each other:
image(images[z], x, y );
您可以在该行之前或之后添加console.log(x,y);
进行仔细检查.
You can add console.log(x,y);
before or after that line to double check.
总体来说,您正在做一个网格,您可能希望该网格的每个元素都是您预先加载的图像,但是您需要将它们隔开一些空间:
Overall you're doing a grid, where you might want each element of that grid to be the images you preloaded, but you need to space them out a bit:
image(images[z], x + images[z].width * z, y );
这是快速且棘手的,但实际上您可以算出所需的间距:total width / (image width + image spacing) = spacing per image
,假设加载的图像大小相同
This is quick and hacky, but you can actually work out how much spacing you need: total width / (image width + image spacing) = spacing per image
, assuming the loaded images are the same size
另一种选择可能是循环浏览阵列中的图像:
Another option might be to cycle through the images from the array:
function draw() {
var i = 0;
//image(images[0],0,0);
for ( var y= 0; y < height; y=y+300) {
for ( var x =0; x < width; x=x+300) {
//using % to loop back to the first element after the array length
image(images[i % images.length], x, y );
i++
}
}
}
请注意,上面的代码尚未经过测试,但是希望它可以被理解以适应
Note that the above code hasn't been tested, but hopefully it will be understandable enough to adapt
这篇关于图像数组p5.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!