Image Object Array not displaying correctly

Need some help trying to make an object image array based on Daniel Shiffman tut, but having this console error while displaying . " image() was expecting p5.Image|p5.Element for the first parameter, received an empty variable instead.". …

let particles = [];
let cells = [];
let sf = 1; 
let x = 0;
let y = 0; 
let mx, my; 
let flagMove;
let  randomImg;

function preload() {
    for (let i = 1; i < 11; i++){
        cells[i] = loadImage('assets/cell-(' + i + ').jpg');
    }
}

function setup() {
    createCanvas(window.innerWidth, window.innerHeight);
    flagMove = 0;
    for (let i = 0; i < width / 4; i++) {
        particles.push(new Particle());
    }
}

function draw() {
    mx = mouseX;
    my = mouseY;
    background(0, 0, 100);
    translate(mx, my);
    scale(sf);
    translate(-mx, -my);


    if (mouseIsPressed) {
        x -= pmouseX - mouseX;
        y -= pmouseY - mouseY;
      }

 
        for (let i = 0; i < particles.length; i++) {
            particles[i].createParticle();
            //particles[i].moveParticle();
            particles[i].joinParticles(particles.slice(i));
        }
}

window.addEventListener("wheel", function(e) {
    if (e.deltaY > 0)
      sf *= 1.05;
    else
      sf *= 0.95;
  });



class Particle {
    constructor() {
        this.x = random(0, width);
        this.y = random(0, height);
        this.r = random(0,50);
        this.xSpeed = random(-2, 2);
        this.ySpeed = random(-1, 1.5);
        this.cell = random(cells);
    }

    // creation of a particle.
    createParticle() {
        noStroke();
        if(sf <= 1){
            fill('rgba(200,169,169,0.5)');
            circle(this.x, this.y, this.r);
        }if(sf > 1){
            image(this.cell, this.x, this.y, this.r, this.r);
            console.log(this.cell);

        }
    }

    // setting the particle in motion.
    moveParticle() {
        if (this.x < 0 || this.x > width)
            this.xSpeed *= -1;
        if (this.y < 0 || this.y > height)
            this.ySpeed *= -1;
        this.x += this.xSpeed;
        this.y += this.ySpeed;
    }


    joinParticles(particles) {
        particles.forEach(element => {
            let dis = dist(this.x, this.y, element.x, element.y);
            if (dis < 60) {
                stroke('rgba(255,255,255');
                line(this.x, this.y, element.x, element.y);
            }
        });
    }
}

Any guesses around here ???

2 Likes

Welcome! Mind sharing a link to your code (e.g., on the p5 Editor)?

You can provide everyone with nicely formatted/color-coded snippets by placing them between pairs of three back ticks ```. For example, here’s how to format JavaScript code:

```javascript
// your code here
```
2 Likes

thanks for the welcome tip @mcintyre !

Here it is the code in p5.editor, trying to make zoom for particle system and change his behaviour from circles to images with the mouse wheel, but could not render images object array properly,guess is related to some syntax problems when calling random images from array object, any suggestion is very welcome, many thanks ! …

https://editor.p5js.org/desarrolloak/sketches/rbOK4wD92

It’s not a syntax issue, but you are correct that it’s an issue with the use a random(cells) to select a random image. The problem is that cells has no item at index 0. Arrays in JavaScript are index by zero, so when you assign an item to position 1 you are leaving an empty slot at 0. Any code that iterates over the items in that array is going to find a value of undefined in that position. Here’s the fix:

    for (let i = 1; i < 11; i++){
        // Note the index: i - 1 instead of just i
        cells[i - 1] = loadImage('assets/cell-(' + i + ').jpg');
    }

Alternately you could use .push():

    for (let i = 1; i < 11; i++){
        cells.push(loadImage('assets/cell-(' + i + ').jpg'));
    }

bonus points, use a template string:

    for (let i = 1; i < 11; i++){
        cells.push(loadImage(`assets/cell-(${i}).jpg`));
    }

more bonus points, use .map():

    cells = [...new Array(10)].map((_, ix) => loadImage(`assets/cell-(${ix + 1}).jpg`));

sorry, I digress.

3 Likes

I couldn’t see it, but now is really really working !!! thank you very much for this guide @KumuPaul , I really appreciate it. I think I forgot how iterating over arrays works. And also this syntax looks fascinating to optimize the code, i will definitely!!!, the syntax in Javascript with p5.js seems very versatile . I hope this questioning functions also for others inquiring into arrays !!! greetings from Mexico :nerd_face: :vulcan_salute: