Skip to content

Instantly share code, notes, and snippets.

@johnniehard

johnniehard/TestSketch.js

Last active Apr 3, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.