I’m having issues understanding how the P5.js instance mode works. The syntax of creating the object seems so different from anything else I’ve seen.
We’re instantiating a new object with the ‘new p5(Sketch)’ statement in UseEffect. Usually to instantiate a new object, an argument is passed that has the necessary requirements for the Constructor in a Class to create. However, in this case, a new object is being instantiated by passing a function as an argument. This seems so different from what I’ve encountered in the past.
I can use these templates and have been able to create my own customized code. However, it bothers me that how this is so different.
I would like to understand the principles. Can someone please explain to me in a detailed manner?I’m a self-taught programmer and am able to code certain work or hobby related requirements. I’m familiar with OOP principles.
I understand the objective is to use the instance mode so that we don’t confuse the common variables/functions with other libraries.
I’ve tried to read as much possible but I’ve not understood the explanations. I had also tried https://github.com/processing/p5.js/wiki/Global-and-instance-mode
The two most confusing lines are:
new p5(Sketch);
const Sketch = p5 => {….}
Here are a few specific questions:
- We’re instantiating a p5 object with a function with the ‘new p5(Sketch’. How is this possible?
- The Sketch function itself has a p5 argument. So, we seem to be instantiating a p5 object with an argument Sketch which itself has a p5 object as an argument. This seems circular.
import React, { useEffect } from "react";
import * as p5 from "p5";
const P5Sketch = () => {
const Sketch = p5 => {
Let radius;
p5.setup = () => {
p5.createCanvas(p5.windowWidth, p5.windowHeight);
p5.background(0);
Radius = 0;
};
p5.draw = () => {
p5.ellipse(p5.width/2,p5.height/2,radius,radius);
radius++;
};
};
useEffect(() => {
new p5(Sketch);
}, []);
return (
<></>
);
};
export default P5Sketch;
I’ve tried to read as much as possible to understand this but not able to grasp it.