// Usage
function App() {
const draw = 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 = useRef(null);
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;
}
TypeScript
복사
Attention: add "draw" to dependency if your draw function depend on other state, or wrap it with useCallback and specify dependency.
주의: 그리기 함수가 다른 상태에 의존할 경우 dependency에 "draw"를 추가하거나
useCallback으로 래핑하여 종속성을 지정합니다.