1

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 Answers1

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

George Profenza
  • 50,687
  • 19
  • 144
  • 218
  • 1
    didn't have any space between images by purpose because i had images 300x300 and the canvas was 900x900 so, wanted to have perfect fit. but the rest worked like a charm. though i didn't get the use of % (modulus) there. I understand that I was drawing the images on top of each other and you incremented the i without the for loop. –  May 20 '17 at 17:58
  • 1
    @PoYo [%(modulo)](https://processing.org/reference/modulo.html) is an operator that returns the remainder of integer. In this case it's an easy way to have an integer `i` that increases beyond `images.length` loop back to 0 when it does. It's a short-hand for using a secondary counter, let's say `j` that would increment along with `i`, but would be reset to `0` if `j == images.length` – George Profenza Jun 01 '17 at 23:32