Skip to content

Instantly share code, notes, and snippets.

@johnniehard
Last active April 3, 2020 19:34
Show Gist options
  • Save johnniehard/088052713d73b6f319c43e6fa69259e1 to your computer and use it in GitHub Desktop.
Save johnniehard/088052713d73b6f319c43e6fa69259e1 to your computer and use it in GitHub Desktop.
Using p5.js with React using custom hook.
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} />
}
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