How do I gain access to a variable from another scope?

Asked

Viewed 49 times

0

P5 is a canvas creation and animation lib.

I got an error when I couldn’t find a variable from a constructor function "sister".

Looking at the sk.draw() Function, the error occurs when this function is searching for a function variable above: sk.setup, How do I pull the variable b of the scope of sk.setup for the scope of my sk.draw function()` ?

follows the code below.

/* eslint-disable */
import * as p5 from 'p5'




let sketch = (p5) => {
    console.log(p5)

    class Boundary {
        constructor(x1, y1, x2, y2) {
            this.a = p5.createVector(x1, y1);
            this.b = p5.createVector(x2, y2);
        }

        show = () => {
            p5.stroke(255);
            p5.line(this.a.x, this.a.y, this.b.x, this.b.y);
        };
    }


    p5.setup = () => {
        // eslint-disable-next-line
        let b
        p5.createCanvas(window.innerWidth, window.innerHeight);
        b = new Boundary(300, 100, 300, 300);
    };


    p5.draw = () => {
        p5.background(0);
        b.show();
    }
}


const P5 = new p5(sketch);

export default P5

1 answer

1

Just move the variable declaration b from within the scope of the function setup() for the scope of the function sketch() tornado b so visible to setup() and draw().

let sketch = () => {

    class Boundary {
        constructor(x1, y1, x2, y2) {
            this.a = createVector(x1, y1);
            this.b = createVector(x2, y2);
        }

        show = () => {
            //Acrescentei essas linhas para explorar alguns recurso da biblioteca.
            //Não são necessárias ao seu código
            strokeWeight(2.0);
            strokeCap(ROUND);            
            textSize(32);
            fill(165, 10, 10);
            text('PT Stack Overflow',mouseX, mouseY); 
            strokeWeight(1.0);
            //**************************************
            stroke(255);
            line(this.a.x, this.a.y, this.b.x, this.b.y);
        };
    }

    let b; //agora b é visível tanto para setup() e draw() 

    setup = () => {         
        createCanvas(window.innerWidth, window.innerHeight);
        b = new Boundary(300, 100, 300, 300);
    };


    draw = () => {
        background(0);
        b.show();
    }

}

sketch();
<script type="module" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.