Added canvas wrapper
This commit is contained in:
parent
cbecf39e88
commit
d8a4852202
@ -4,6 +4,7 @@
|
|||||||
"description": "Web application for distribution of free classrooms",
|
"description": "Web application for distribution of free classrooms",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
"start": "vite",
|
||||||
"build": "vite build"
|
"build": "vite build"
|
||||||
},
|
},
|
||||||
"author": "dm1sh",
|
"author": "dm1sh",
|
||||||
|
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} />;
|
||||||
|
};
|
Loading…
x
Reference in New Issue
Block a user