Instance mode : accessing `p5` functions in an external class

Hi everyone !

I’m using p5.js in a project (code here). I have to use p5.js in instance mode and attach the p5 object to the canvas which is just working fine so far.

Now I would like to create a class in a separate folder Chiffre.js where I would like to use p5 functionalities, like vectors for example, as in the one below:

class Chiffre {
  constructor(x, y, signe) {
    this.signe = signe;
    this.position = createVector(x, y);
    this.vitesse = createVector(0, 0);
    this.acceleration = createVector(0, 0);
  }
}

export { Chiffre };

Now in the file zone.js where the p5 object is created, I have something like this:

import { Chiffre } from "./Chiffre.js";

export const sketch = (s) => {
  s.chiffre = new Chiffre(20, 20, "2");
};

and in the page (actually, it’s a Vue component) where the p5 object is used, I have something like this:

import p5 from "p5";
import { sketch } from "../js/zone.js";
let d = new p5(sketch, "p5Canvas");

It does not work because the createdVector function is not recognized :thinking:

ReferenceError: createVector is not defined

I cannot figure out how to access p5 reference functions inside my class.

Does anybody has any idea how to solve this problem?

Request a p5 object as 1 of the constructor’s parameters:

And pass it when instantiating the class:

The code above should work if that parameter s happens to be of datatype p5.

For more examples of classes which also request a p5 object take a look at the sketch below:

Nice, it’s working but instead of

this.position = p.createVector(x, y);

I replaced it with

this.position = this.p.createVector(x, y);

Am I right or not ?

Actually both yours & mine are correct inside the constructor(), b/c the parameter p is the same as property this.p (Chiffre::p): :wink:

You’re right. But in a show() function outsite the constructor: this is required though…

show() {
    this.p.text(this.signe, this.position.x, this.position.y);
  }

Yea, b/c it doesn’t make sense to pass a p5 object again for the show() method given it’s stored as a Chiffre property named p already.

But in order to avoid repeating the keyword this all the time you can use JS object destructuring assignment syntax:

That’s really nice :star_struck:. Thanks for the tip!

1 Like