javascriptp5.js

Dependency in p5.js instance mode without passing the instance


From what I've gathered, using global mode in p5 is discouraged because it pollutes the global namespace. I have used instance mode for a while, but creating dependencies is always frustrating. In order to use p5 functions, all of my functions in other files have to have the whole p5 instance passed into them. If I'm creating a bunch of entities in a project, I'm wasting a whole bunch of resources by having each of them contain the whole p5 library essentially. Is there any better way to approach this?


Solution

  • In my understanding, you don't have to "pass" the p5 instance into your functions in other files. The p5 instance should be declared global. This should not use more resources than in the global mode case.

    So rather than having all the p5 functions attached to the global window object (the global mode), now we have all of them attached to the global p5 instance object (the instance mode). It's just a matter of namespace.

    Consider the example below, which is a modified version of an example on p5 website:

    //sketch.js
    let sketch = function(p) {
      let x = 100;
      let y = 100;
    
      p.setup = function() {
        p.createCanvas(700, 410);
        p.background(0);
      };
    
      p.draw = function() {
        p.fill(255);
        p.rect(x, y, 50, 50);
      };
    };
    
    var myp5 = new p5(sketch);
    

    And you can manipulate the global myp5 instance in other files. For example, in your other.js:

    //other.js
    function randomBackgroundColor() {
      myp5.background(myp5.random(0, 255));
    }
    
    setInterval(randomBackgroundColor, 1000); //change background color every 1000 milliseconds
    

    Including these two js files (with sketch.js first) in your html file results in a canvas with a changing background and a rectangle.