P5 standalone build for Browserify

Hi All,

I’m trying to create a p5 standalone build with Browserify. I’ve installed the p5 package and following this stack overflow thread, I was able to export the p5 object and run the following code in my client.js:

const p5 = require("p5");
...
module.exports = new p5(function() {
  this.setup = function setup() {
    p5setup();
    messageUI();
    socketPeer();
  };
  this.draw = function draw() {
    p5text();
  };
});

function p5setup() {
  this.createCanvas(this.windowWidth, this.windowHeight);
  cg1 = this.createGraphics(this.windowWidth, this.windowHeight);
  this.background(bg);
  this.textSize(36);
  this.textFont("Lora");
  this.noStroke();
}

function p5text() {
  cg1.background(255);
  if (incomingMsg && x1 && y1) {
    this.fill(c1);
    this.text(incomingMsg, x1, y1, txtW);
    if (c1 < 255) {
      c1 += 0.5;
    }
  }
  if (outgoingMsg && x2 && y2) {
    this.fill(c2);
    this.text(outgoingMsg, x2, y2, txtW);
    if (c2 < 255) {
      c2 += 0.5;
    }
  }
  this.image(cg1, 0,0);
}

The full running code is here. Now I’d like to integrate the following class into p5, so that I could display the objects for the TrainCars class inside of draw(), but I’m feeling lost on how to do that:

class TrainCars {
  constructor(){
    this.x = 0;
    this.c = color(255, 0 , 0);
  }
  display(){
   fill(this.c);
   rect(this.x,50,100,50);
  }
  move(){
    this.x = this.x + 1;
  }
}

If you have any tips or can point me to resources that would help me understand this better that would be amazing. Thank you :pray:t3:

Hey @xinxin, if I’m understanding your question, one way you might be able to solve this is by making your TrainCars constructor take a p5 object instance as an argument and storing it as a member variable, so that you can use it later when you call color, fill, etc. from inside the class.

class TrainCars {
  constructor(p5obj){
    this.x = 0;
    this.p5obj = p5obj;
    this.c = this.p5obj.color(255, 0 , 0);
  }
  display(){
   this.p5obj.fill(this.c);
   this.p5obj.rect(this.x,50,100,50);
  }
  move(){
    this.x = this.x + 1;
  }
}

then in p5setup() I think something like this:

let trainCars; // (global scope)

function p5setup() {
  trainCars = new TrainCars(this);
  // and other code...
}

I haven’t tried running this so I’m not 100% sure it will work, but I hope this helps!

1 Like