Skip to content

Instantly share code, notes, and snippets.

@Melvynx
Created August 26, 2022 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Melvynx/b96b1f05b133d7a4d7a13635d0f4892d to your computer and use it in GitHub Desktop.
Save Melvynx/b96b1f05b133d7a4d7a13635d0f4892d to your computer and use it in GitHub Desktop.
Canvas example
export const Canvas = () => {
const canvas = useRef(null);
const isDrawing = useRef(false);
const prevMouse = useRef(null);
const startDrawing = (event) => {
isDrawing.current = true;
prevMouse.current = getCoordinates(event, canvas.current);
};
const stopDrawing = () => {
isDrawing.current = false;
prevMouse.current = null;
};
const draw = (e: MouseEvent) => {
if (!isDrawing.current) return;
const context = canvas.current?.getContext('2d');
const mouse = getCoordinates(e, canvas.current);
if (!context || !mouse) return;
if (prevMouse.current) {
context.lineWidth = 2;
context.lineCap = 'round';
context.lineJoin = 'round';
context.strokeStyle = '#000';
context.beginPath();
context.moveTo(prevMouse.current.x, prevMouse.current.y);
context.lineTo(mouse.x, mouse.y);
context.stroke();
}
prevMouse.current = mouse;
};
return (
<canvas
onMouseDown={startDrawing}
onMouseMove={draw}
onMouseLeave={stopDrawing}
onMouseUp={stopDrawing}
width={200}
height={200}
ref={canvas}
className="m-auto bg-white rounded-md shadow-md"
/>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment