P5 image and class

Hi!

I’m having trouble with the image function in p5.

I’m following Dan Shiffman tutorial: https://youtu.be/i2C1hrJMwz0

I keep getting the following friendly message : :cherry_blossom: p5.js says: image() was expecting p5.Image|p5.Element for the first parameter, received string instead. (on line 106 in about:srcdoc [about:srcdoc:106:5]). (reference | p5.js)

I don’t know what is wrong.

Here is my code:

let girls = [];
let img;

function preload() {
  img = ('images/personnage-principal-mini-manon.png');
}

function setup() {
    createCanvas(1200, 700);
    for (let i = 0; i < 10; i++) {
    girls[i] = new Girl(random(width), random(height));
  }
}

function draw() {
  background(220);
  for (let i = 0; i < girls.length; i++) {
    girls[i].move();
    girls[i].show();
  }
}

class Girl {
  constructor (tempX, tempY) {
    this.x = tempX;
    this.y = tempY;
  }
  
  move() {
    this.x = this.x + random(-5, 5);
    this.y = this.y + random(-5, 5);
  }
  
  show() {
    image(img, this.x, this.y);
  }
}

p5js.org/reference/#/p5/loadImage

1 Like

This is exactly what I’m doing.

It works fine as long as I don’t use it into a class.

But when I insert image(img, x, z) in a class, it does not work anymore.

Hi @vlafortune,

You have this, which does not call the loadImage function:

  img = ('images/personnage-principal-mini-manon.png');

Try this, and it should work, provided that the path to the image file is correct:

  img = loadImage('images/personnage-principal-mini-manon.png');
1 Like

Hi @javagar. Thank you. This solves everything. I hadn’t seen the error!

1 Like