Last active
April 3, 2020 19:34
-
-
Save johnniehard/088052713d73b6f319c43e6fa69259e1 to your computer and use it in GitHub Desktop.
Using p5.js with React using custom hook.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import useSketch from "."; | |
export default function TestSketch() { | |
const sketch = useSketch(s => { | |
s.setup = () => { | |
s.createCanvas(800, 600) | |
} | |
s.draw = () => { | |
s.background(0) | |
s.fill(255) | |
s.rect(s.mouseX, s.mouseY, 50, 50) | |
} | |
}) | |
return <div ref={sketch} /> | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import p5 from 'p5' | |
// or just download the p5.min.js from https://p5js.org/download and drop it in your source folder since the npm | |
// version is not minified and clocks and at something like 5MB | |
//import p5 from './p5.min.js' // now that's better, ~650kb, ~150kb gzipped | |
import { useEffect, useRef } from 'react' | |
export default function useSketch(sketch) { | |
const domRef = useRef(null) | |
useEffect(() => { | |
new p5(sketch, domRef.current) | |
}, []) | |
return domRef | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment