Skip to content

Instantly share code, notes, and snippets.

@lucas-lm
Created March 7, 2020 01:18
Show Gist options
  • Save lucas-lm/e5f2c236b27273c6597ab9a36de5256b to your computer and use it in GitHub Desktop.
Save lucas-lm/e5f2c236b27273c6597ab9a36de5256b to your computer and use it in GitHub Desktop.
React custom hook for using canvas
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