Manipulating the canvas is a mutable task, so performing this in react would require proper handling to prevent multiple rerenders
Example of drawing in the canvas
const Canvas = () => {
const ref = useRef()
useEffect(() => {
const context = ref.current.getContext("2d")
context.beginPath();
context.lineTo(10, 10);
context.fill();
}, [ref])
return <canvas ref={ref}>
}
Yes, though now since the canvas can be represented as a component, I can store the canvas's context in a React Context and reuse it
// Canvas
export default ({ children }) => {
const [context, setContext] = useState();
const ref = useRef(null);
useEffect(() => {
setContext(ref.current.getContext("2d"));
}, [ref]);
return (
<CanvasProvider value={context}>
<canvas ref={ref} />
{children}
</CanvasProvider>
);
}
// Square.js
export default ({ length, x, y }) => {
const context = useContext(CanvasContext);
if (context != null) {
context.beginPath();
context.rect(x, y, length, length);
context.stroke();
}
return <></>;
};
// home.jsx
<Canvas>
<Square length={40} x={0} y={0} />
</Canvas>
I'll cover this in another example
You can see the previous example live here
The source here
I used this article as reference. My idea is to get more people aware of this concept and the extensibility you can achieve with this
The image I drew is from an example in generativeartistry by tholman