Added canvas wrapper

This commit is contained in:
Dmitriy Shishkov 2021-09-04 03:09:24 +03:00
parent cbecf39e88
commit d8a4852202
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060
2 changed files with 29 additions and 0 deletions

View File

@ -4,6 +4,7 @@
"description": "Web application for distribution of free classrooms",
"scripts": {
"dev": "vite",
"start": "vite",
"build": "vite build"
},
"author": "dm1sh",

28
src/components/Canvas.tsx Normal file
View 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} />;
};