Added click event wrapper in Canvas component
This commit is contained in:
parent
8425cff7b5
commit
40c68338ab
@ -50,7 +50,14 @@ export const BuildingPlan = ({ width, height }: BuildingPlanProps) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Canvas height={height} width={width} draw={draw} />
|
<Canvas
|
||||||
|
clickCb={(x, y) => {
|
||||||
|
console.log(`x: ${x}, y: ${y}`);
|
||||||
|
}}
|
||||||
|
height={height}
|
||||||
|
width={width}
|
||||||
|
draw={draw}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
@ -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 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);
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -18,11 +23,25 @@ export const useCanvas = (draw: DrawFT) => {
|
|||||||
draw(context);
|
draw(context);
|
||||||
}, [draw]);
|
}, [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) => {
|
export const Canvas = ({ draw, clickCb, ...props }: CanvasProps) => {
|
||||||
const canvasRef = useCanvas(draw);
|
const { canvasRef, onClick } = useCanvas(draw, clickCb);
|
||||||
|
|
||||||
return <canvas ref={canvasRef} {...props} />;
|
return <canvas onClick={onClick} ref={canvasRef} {...props} />;
|
||||||
};
|
};
|
||||||
|
Loading…
x
Reference in New Issue
Block a user