Added click event wrapper in Canvas component

This commit is contained in:
Dmitriy Shishkov 2021-09-04 04:57:54 +03:00
parent 8425cff7b5
commit 40c68338ab
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060
2 changed files with 34 additions and 8 deletions

View File

@ -50,7 +50,14 @@ export const BuildingPlan = ({ width, height }: BuildingPlanProps) => {
return (
<>
<Canvas height={height} width={width} draw={draw} />
<Canvas
clickCb={(x, y) => {
console.log(`x: ${x}, y: ${y}`);
}}
height={height}
width={width}
draw={draw}
/>
</>
);
};

View File

@ -1,10 +1,15 @@
import { HTMLProps, useEffect, useRef } from "react";
import { HTMLProps, useEffect, useRef, MouseEvent, useCallback } from "react";
export type DrawFT = (ctx: CanvasRenderingContext2D) => void;
export type CanvasProps = HTMLProps<HTMLCanvasElement> & { draw: DrawFT };
export type ClickCb = (x: number, y: number) => void;
export const useCanvas = (draw: DrawFT) => {
export type CanvasProps = HTMLProps<HTMLCanvasElement> & {
draw: DrawFT;
clickCb: ClickCb;
};
export const useCanvas = (draw: DrawFT, clickCb: ClickCb) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
@ -18,11 +23,25 @@ export const useCanvas = (draw: DrawFT) => {
draw(context);
}, [draw]);
return canvasRef;
const onClick = useCallback(
(event: MouseEvent<HTMLCanvasElement>) => {
const canvas = canvasRef.current;
if (!canvas) throw new Error("Canvas ref not set");
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
clickCb(x, y);
},
[canvasRef.current]
);
return { canvasRef, onClick };
};
export const Canvas = ({ draw, ...props }: CanvasProps) => {
const canvasRef = useCanvas(draw);
export const Canvas = ({ draw, clickCb, ...props }: CanvasProps) => {
const { canvasRef, onClick } = useCanvas(draw, clickCb);
return <canvas ref={canvasRef} {...props} />;
return <canvas onClick={onClick} ref={canvasRef} {...props} />;
};