This hook provides a simple API for rendering animations with <canvas/>
.
The hook takes a renderer
function, that should return a function that will be called in a loop
on each animation frame.
The renderer
function will be called with a CanvasRenderingContext2D
object, which you can use to draw on the canvas.
The reason for using a function that returns a function is to allow you to set up values that will be used across renders.
import { useRef, useEffect } from 'react';
export const useCanvasAnimation = (renderer) => {
const canvas = useRef();
const frameId = useRef(0);
useEffect(() => {
const render = renderer();
const update = () => {
frameId.current = requestAnimationFrame(() => {
render(canvas.current?.getContext('2d'));
update();
});
};
update();
return () => cancelAnimationFrame(frameId.current);
}, [renderer]);
return canvas;
}
You can use it like so:
const Example = () => {
const canvas = useCanvasAnimation(() => {
// Use this part to initialze values to be used across renders
return (ctx) => {
// Render something using the context in ctx
};
});
return (
<canvas ref={canvas}/>
)
}
In the example below, we use the useCanvasAnimation
hook to create a simple
animation that draws a circle that moves across the canvas.
The renderer
function is called on each animation frame, and it updates the position of the circle and redraws it.