Create Array of Images ? - Novice p5 user

Hi!

So I am new to p5.js and I am creating something of a simulator. I want to make an array of images (I have the image files created and put in my libraries folder) instead of an array of words.

http://p5js.org/reference/#/p5/random The final example on this p5 random page is what I'm going for, just with images.

In general, my code looks like: var image1; var image2; ... var imagesarray;

function preload(){ image1=loadImage("libraries/image1.png"); .. }

function xyz(){ var imagesarray=[image1,image2...]; for (var i=0; i<10; i++){ push(); translate(random(width),random(height)); var index2=floor(random(imagesarray.length)); text(imagesarray[index2],0,0,300,300);
} }

Can you make an array of images, if so, how?

Tagged:

Answers

  • edited December 2015

    We can't read your code messed up like that:
    https://forum.Processing.org/two/discussion/8045/how-to-format-code-and-text

    Just a sample attempt below. WARNING: Not tested!

    // forum.Processing.org/two/discussion/13735/
    // create-array-of-images-novice-p5-user
    
    // GoToLoop (2015-Dec-01)
    
    const PATH = 'data/', FILE = 'image', EXT = '.png';
    const IMAGES = 4, imgs = Array(IMAGES);
    var idx = 0;
    
    function preload() {
      for (var i = 0; i != IMAGES; 
        imgs[i] = loadImage(PATH + FILE + ++i + EXT));
    }
    
    function setup() {
      createCanvas(800, 600);
      noLoop();
    }
    
    function draw() {
      background(imgs[idx]);
    }
    
    function mousePressed() {
      idx = ~~random(IMAGES);
      redraw();
    }
    
  • @GoToLoop: using a relatively obscure bitwise operator in code intended for a 'Novice p5 user' is not especially helpful; and you've gained very little if anything in terms of performance over using Math.floor(); particularly since this isn't a processor intensive situation...

    Anyone would think you deliberately obfuscate your code for the sake of brevity :P

Sign In or Register to comment.