Sketch with classes implementation in a Reactjs project

Hi @GoToLoop thank you for your reply :+1:

I feel I didn’t explain my problem very well. I’m not an expert in Javascript so some of its quirks are still a mistery to me hence my post. p5js can be imported, here is an example of a bare-bones component.

import p5 from 'p5';

export default function P5Component() {
	const sketch = (p) => {
		p.setup = () => {
			p.createCanvas(window.innerWidth, window.innerHeight);
			p.background('#fcfcfc');
		};

		p.draw = () => {
			p.background('#fcfcfc');
			p.fill(20, 20);
			p.ellipse(p.mouseX, p.mouseY, 50, 50);
		};
	};
	new p5(sketch, window.document.getElementById('canvasContainer'));
	return null;
}

You must install the package on to your React project.

My struggle comes when I need to use other third party libraries and clases in my project, so I wondered if there is an easier way to work with such combination.

So on my project I import the Matterjs library and a Class, passing a p5 reference to the class is not a problem, as you suggested :+1:

But when the class needs to use some of the Matterjs objects and methods things start to get complicated. I already try to pass a reference of Matterjs, but I happen to import all sort of objects Bodies, Constrains, World and so on and still cant get it to work. I think I’ll have to keep all my code in the same Component and not border with a class since my skectch is very small.

Say your bouncing ball instance mode code, is a good example of my situation. If you make the ball a class in a separate file that uses Matterjs to bounce around will mirror my situation exaclty.

Again if there is a way to workaround this kind of situations I’ll love to know about it.

1 Like