0
export class MyComponent implements OnInit
{
    private p5;

    myWidth = 200;

    private sketch(p: p5) {
        p.setup = () => {
          let canvas = p.createCanvas(this.myWidth, this.myWidth);
        };

        p.draw = function(){
          p.background(255);
          p.fill(0);
          p.rect(p.width / 2, p.height / 2, 50, 50);
        };
    }

    private createTheCanvas() {
        this.p5 = new p5(this.sketch);
    }

    ngOnInit()
    {
        this.createTheCanvas();
    }
}

Here, the error is this.myWidth is undefined

Now the question is how do I access variables in class MyComponent in draw or setup function of p5

Adrian Fâciu
  • 11,776
  • 3
  • 50
  • 66
Mukund
  • 19
  • 3
  • You can give an execution context to the function, for example using bind: new p5(this.sketch.bind(this)). Have a look [here](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work#3127609) to understand more about this in js. – Adrian Fâciu Aug 22 '18 at 18:46
  • Hmm... @MattMcCutchen isn't the `this.myWidth` in a lambda? It should not have a separate context. – Michał Karpacki Aug 22 '18 at 19:05
  • The `this.myWidth` has the same context as the surrounding `sketch` method. The problem is the line in `createTheCanvas` that passes `this.sketch` to `new p5`. – Matt McCutchen Aug 22 '18 at 19:23

0 Answers0