Skip to content

Instantly share code, notes, and snippets.

@maltoze
Created March 18, 2021 02:03
Show Gist options
  • Save maltoze/919c671dd33b3c237b510c9acf23861a to your computer and use it in GitHub Desktop.
Save maltoze/919c671dd33b3c237b510c9acf23861a to your computer and use it in GitHub Desktop.
import { useEffect, useRef } from 'preact/hooks';
import { Cord } from 'src/types';
const QuadsDrawableCanvas = () => {
const canvasRef = useRef<HTMLCanvasElement>();
const cordArrRef = useRef<Cord[]>([]);
const initSizeRef = useRef<boolean>(false);
const handleCanvasMouseDown = (e: MouseEvent) => {
e.preventDefault();
const canvas = canvasRef.current;
if (!initSizeRef.current) {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
initSizeRef.current = true;
}
const ctx = canvas.getContext('2d');
if (!ctx) return;
const cordArr = cordArrRef.current;
if (cordArr.length >= 4) {
cordArrRef.current = [];
ctx.clearRect(0, 0, canvas.width, canvas.height);
return;
}
const offset = canvas.getBoundingClientRect();
const x = e.clientX - offset.left;
const y = e.clientY - offset.top;
cordArr.push({ x, y });
if (cordArr.length === 4) {
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.closePath();
ctx.stroke();
}
};
const handleCanvasMouseMove = (e: MouseEvent) => {
const cordArr = cordArrRef.current;
if (cordArr.length === 0 || cordArr.length > 3) return;
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
cordArr.forEach((cord, idx) => {
if (idx === 0) {
ctx.moveTo(cord.x, cord.y);
} else {
ctx.lineTo(cord.x, cord.y);
}
});
const offset = canvas.getBoundingClientRect();
const mouseX = e.clientX - offset.left;
const mouseY = e.clientY - offset.top;
ctx.lineTo(mouseX, mouseY);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.stroke();
};
const handleResize = () => {
const canvas = canvasRef.current;
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
};
useEffect(() => {
const canvas = canvasRef.current;
canvas.addEventListener('mousedown', handleCanvasMouseDown);
canvas.addEventListener('mousemove', handleCanvasMouseMove);
window.addEventListener('resize', handleResize);
return () => {
canvas.removeEventListener('mousedown', handleCanvasMouseDown);
canvas.removeEventListener('mousemove', handleCanvasMouseMove);
window.removeEventListener('resize', handleResize);
};
}, []);
return <canvas className="position-absolute w-100 h-100" ref={canvasRef} />;
};
export default QuadsDrawableCanvas;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment