Skip to content

Instantly share code, notes, and snippets.

@IcanDivideBy0
Last active September 28, 2021 03:14
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save IcanDivideBy0/23552eb3aa196a9049670686d13de9de to your computer and use it in GitHub Desktop.
Save IcanDivideBy0/23552eb3aa196a9049670686d13de9de to your computer and use it in GitHub Desktop.
Simple hook for canvas rendering in react
import React from "react";
// Usage
function App() {
const draw = React.useCallback(gl => {
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clearDepth(1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
}, []);
const canvasRef = useCanvas(draw, "webgl2");
return <canvas ref={canvasRef} width="800" height="600" />;
}
// Hook
function useCanvas(draw, context = "2d") {
const canvasRef = React.useRef(null);
React.useEffect(() => {
const ctx = canvasRef.current.getContext(context);
let animationFrameId = requestAnimationFrame(renderFrame);
function renderFrame() {
animationFrameId = requestAnimationFrame(renderFrame);
draw(ctx);
}
return () => cancelAnimationFrame(animationFrameId);
}, [draw, context]);
return canvasRef;
}
@XHMM
Copy link

XHMM commented Jun 27, 2019

Attention: add draw to deps if your draw function depend on other state, or wrap it with useCallback and specify deps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment