Search code examples
javascriptp5.js

Passing in extra argument to new p5 instance


I need to pass in an additional argument when invoking a new p5 instance in instance mode.

I want to be able to do this:

var x = 50;

var sketch = function(p5){

  p5.setup = function(x){
    // Canvas setup etc
    rect(x,40,40,40)
  }
}

new p5(sketch, x)

Right now, it's showing as undefined, which leads me to believe that new p5 can only ever take one argument. Is there a method available that allows me to pass in additional arguments to an instance, without hacking p5?


Solution

  • Yeah, you can't just add random parameters to the p5 object like that. Also note that the p5 constructor and the setup() function are two entirely different things. You call the constructor, and the P5.js library calls the setup() function for you.

    I'm really not sure what you're trying to do. Why don't you just get rid of the x parameter (which is undefined) and reference the top-level x variable (which is 50)?

    You might be able to do something slightly goofy, like this:

    function defineSketch(x){
    
      return function(sketch){
        sketch.setup = function(){
          // Canvas setup etc
          rect(x,40,40,40)
        }
      }
    }
    

    And then you could do:

    var mySketch = defineSketch(100);
    new p5(mySketch);
    

    That's pretty gross though.

    Edit: You can also do this:

    var s = function( sketch ) {
    
      sketch.setup = function() {
        sketch.createCanvas(200, 200);
      };
    
      sketch.draw = function() {
        sketch.background(0);
        sketch.rect(sketch.x, sketch.y, 50, 50);
      };
    };
    
    var myp5 = new p5(s);
    myp5.x = 75;
    myp5.y = 25;
    

    This works because sketch is the instance of p5 that you create. So you can add properties to the p5 instance, which is passed into your sketch function.