Added canvas wrapper
This commit is contained in:
28
src/components/Canvas.tsx
Normal file
28
src/components/Canvas.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import { HTMLProps, useEffect, useRef } from "react";
|
||||
|
||||
export type DrawFT = (ctx: CanvasRenderingContext2D) => void;
|
||||
|
||||
export type CanvasProps = HTMLProps<HTMLCanvasElement> & { draw: DrawFT };
|
||||
|
||||
export const useCanvas = (draw: DrawFT) => {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) throw new Error("Canvas ref not set");
|
||||
|
||||
const context = canvas.getContext("2d");
|
||||
|
||||
if (!context) throw new Error("Couldn't get canvas context");
|
||||
|
||||
draw(context);
|
||||
}, [draw]);
|
||||
|
||||
return canvasRef;
|
||||
};
|
||||
|
||||
export const Canvas = ({ draw, ...props }: CanvasProps) => {
|
||||
const canvasRef = useCanvas(draw);
|
||||
|
||||
return <canvas ref={canvasRef} {...props} />;
|
||||
};
|
Reference in New Issue
Block a user