How to adapt a library for Instance Mode (P5JS)

  • Now the solution you’re looking for: Not request the p5 object from your library’s user!
  • You already know by now that directly instantiating classes using the keyword new can’t consistently get a sketch’s p5 object, unless they require it as their constructor()'s parameter.
  • There are some workarounds though like p5.instance, p5.Element::pInst, p5.Vector::p5, etc.
  • However, they’re all circumstantial and don’t work for all cases.
  • What you need to do instead is adding an instantiator method in the class p5’s prototype{} object.
  • B/c it’s a p5 method, it automatically receives the p5’s object via the keyword this every time it’s invoked!
  • That’s exactly how p5 methods like createVector(), createCanvas(), createGraphics(), createElement(), etc. work!
  • They all instantiate a class in our place passing the p5’s this as 1 of the arguments behind-the-scenes.
  • You’d only need to advice your library’s users to prefer those createXXX() methods rather than directly instantiating a class via new:
p5.prototype.createWord3D(string, depth, size, resolution, bevelled, font, style) {
  return new Word3D({ p: this, string, depth, size, resolution, bevelled, font, style });
}
1 Like