Created
March 7, 2020 01:18
-
-
Save lucas-lm/e5f2c236b27273c6597ab9a36de5256b to your computer and use it in GitHub Desktop.
React custom hook for using canvas
This file contains 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 { useRef, useEffect } from 'react' | |
const useCanvas = (draw) => { | |
const canvasRef = useRef(null) | |
useEffect(() => { | |
const canvas = canvasRef.current | |
const context = canvas.getContext('2d') | |
let requestAnimationId | |
let counter = 0 | |
const render = ctx => { | |
ctx.save() | |
ctx.clearRect(0, 0, canvas.width, canvas.height) | |
draw(ctx, counter) | |
ctx.restore() | |
counter++ | |
requestAnimationId = requestAnimationFrame(() => render(ctx)) | |
} | |
render(context) | |
return () => { | |
cancelAnimationFrame(requestAnimationId) | |
} | |
}) | |
return canvasRef | |
} | |
export default useCanvas |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment