Last active
September 28, 2021 03:14
-
-
Save IcanDivideBy0/23552eb3aa196a9049670686d13de9de to your computer and use it in GitHub Desktop.
Simple hook for canvas rendering in react
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 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Attention: add
draw
to deps if yourdraw
function depend on other state, or wrap it with useCallback and specify deps