Skip to content

Instantly share code, notes, and snippets.

@AdamSpannbauer
Last active January 22, 2021 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdamSpannbauer/1b64e34307b65f88146074103271c928 to your computer and use it in GitHub Desktop.
Save AdamSpannbauer/1b64e34307b65f88146074103271c928 to your computer and use it in GitHub Desktop.
A base class for a p5js React Component
/*
A base class to create p5js sketches as React components.
Requires p5js: `npm install p5`
## Usage
### Extend Sketch and create a p5js sketch
```
// In `MySketch.js`
import Sketch from "./SketchBase";
export default class MySketch extends Sketch {
Sketch = (p) => {
p.setup = () => {
p.createCanvas(512, 512);
}
p.draw = () => {
p.background(20);
p.ellipse(p.width / 2, p.height / 2, 100);
}
}
}
```
### Use subclassed Sketch component
```
// In `App.js`
import MySketch from "./MySketch";
export default function App() {
return (
<div className="App">
<MySketch />
</div>
);
}
```
*/
import React from 'react';
import p5 from 'p5';
export default class Sketch extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
Sketch = (p) => {
throw new Error(
`NotImplementedError: must define Sketch method with a setup & draw
Example:
export default class MySketch extends Sketch {
Sketch = (p) => {
p.sketch = () => {
p.createCanvas(512, 512);
}
p.draw = () => {
p.background(20);
p.ellipse(p.width / 2, p.height / 2, 100);
}
}
}`
)
}
componentDidMount() {
this.myP5 = new p5(this.Sketch, this.myRef.current);
}
render() {
return (
<div ref={this.myRef}>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment