Image array p5.js

2019-07-27 23:02发布

问题:

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 );
      }
    }
  }
}

as images, i just used 300x300 jpgs 3 of them to test out.

回答1:

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 );

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 );

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