Home > Enterprise >  p5.js Instance Mode: How to access the instance variables from inside a class
p5.js Instance Mode: How to access the instance variables from inside a class

Time:11-24

I'm having trouble using p5js in instance mode. I split my code into multiple files for easier maintenance, separating classes from the main sketch file.

Inside the classes i need access to variables declared in the main sketch but i get undefined when i inject the sketch object into the class.

Ideally i would like to have access to ANY variables declared in the main sketch file. Is it possible/recommended?

Here is a minimum case example of what i'm trying to achieve:

index.js

import p5 from "p5"
import TestClass from "./_testClass";

let sketch = new p5( (p) => {
    let myColor = 75;

    p.setup = function() {
        p.createCanvas(1000,1000);
        let t = new TestClass(100,100)
        t.render(p)
    }
}, "p5");

_testClass.js

export default class TestClass {
    constructor(x,y) {
        this.x = x;
        this.y = y;
    }
    
    render(p) {
        p.rect(this.x, this.y, 50, 50); // i get a square on the canvas: p.rect() is recognized
        console.log(p.myColor); // undefined
    }
}

CodePudding user response:

Any variables that you want to be available within the TestClass's render() function either need to be 1) passed to the TestClass constructor, 2) passed to the render function, 3) declared/assigned on/to the p5 instance, or 4) declared globally.

For instance mode sketches it is not uncommon to add things to the p5 instance:

import p5 from "p5"
import TestClass from "./_testClass";

let sketch = new p5((p) => {
    // let myColor = 75;
    p.myColor = 75;

    p.setup = function() {
        p.createCanvas(1000,1000);
        let t = new TestClass(100,100)
        t.render(p)
    }
}, "p5");

However, I think it would be better OOP practice to pass this to your TestClass constructor:

import p5 from "p5"
import TestClass from "./_testClass";

let sketch = new p5((p) => {
    let myColor = 75;

    p.setup = function() {
        p.createCanvas(1000, 1000);
        let t = new TestClass(100, 100, myColor)
        t.render(p)
    }
}, "p5");

export default class TestClass {
    constructor(x, y, rectColor) {
        this.x = x;
        this.y = y;
        this.rectColor = rectColor;
    }
    
    render(p) {
        console.log(this.rectColor);
        p.fill(this.rectColor);
        p.rect(this.x, this.y, 50, 50);
    }
}
  • Related