1

In the code below, I'm looping through each "player_visualizer" element and attempting to create a new P5 instance for each element.

If I console.log(context) in the loop I will get the context of that particular element, which is exactly what I need.

$('.player_visualizer').each(function (i) {

  context = $(this);

  playerVisualizersP5[i] = new p5(playerVisualizer, context);

});

However, The trouble I'm having is passing the context of that particular element to the function that will handle all of the P5 animations.

For example, when I try and pass that context variable to the function below and do console.log(p.context), the context variable is always undefined.

 let playerVisualizer = function (p, context) {

      p.context = context;

 }

I've done a fair amount of research on what I could do about this, but I can't seem to tie it back to my particular situation. I've narrowed down my research to a few resources below.

http://hugoware.net/blog/passing-context-with-javascript

How do I pass the this context to a function?

Any help or guidance is greatly appreciated.

1 Answers1

0

Why do you believe that passing something into the p5 constructor will automatically pass that argument into the playerVisualizer function?

From the P5.js documentation:

One final note: when creating a p5 instance, you can specify a second argument (HTML element id) which acts the parent for all elements created by the sketch. For example, let's say you have:

<body>
  <div id = "p5sketch">
  </div>

  <p>Some other HTML</p>
</body>

You can now say:

var myp5 = new p5(s,'p5sketch');

And all elements will be created inside that div.

This means the only valid second argument is a string ID, which gets used by P5.js but isn't passed into the sketch function.

To understand better what's going on, let's look at this example:

var s = function( sketch ) {
  sketch.setup = function() {
    sketch.createCanvas(200, 200);
  };

  sketch.draw = function() {
        sketch.background(128);
  };
};

var myp5 = new p5(s);

In this example sketch, there are a few things to understand:

  • myp5 is an instance of p5, which contains P5.js functions like setup() and draw() and background().
  • s is a sketch function, which takes an instance of p5.
  • sketch is an instance of p5, which s can use to access P5.js functions.

In other words, myp5 and sketch are the same object.

This is useful to you, because if you want to pass data into sketch, you can pass that data into myp5, like this:

var s = function( sketch ) {


  sketch.setup = function() {
    sketch.createCanvas(200, 200);
  };

  sketch.draw = function() {
        sketch.background(128);
        sketch.text(sketch.extraThing, 20, 20);
  };
};

var myp5 = new p5(s);
myp5.extraThing = "testing";
Kevin Workman
  • 39,413
  • 8
  • 61
  • 94