Canvas

mail@pastecode.io avatar
unknown
tsx
2 years ago
1.3 kB
2
Indexable
Never
import React, { MouseEvent, useEffect, useRef, useState } from 'react';

export const HTML5Canvas = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const canvasCurrent = canvasRef.current;
  const { current: ctxCurrent } = useRef<CanvasRenderingContext2D>(null);
  const [drawing, setDrawing] = useState(false);
  const [hue, setHue] = useState(100);

  const onDraw = ({ nativeEvent: { offsetX, offsetY } }: MouseEvent<HTMLCanvasElement>) => {
    if (!drawing || !canvasCurrent || !ctxCurrent) {
      return;
    }

    ctxCurrent.lineTo(offsetX, offsetY);
    ctxCurrent.stroke();
  };

  const startDraw = ({ nativeEvent: { offsetX, offsetY } }: MouseEvent<HTMLCanvasElement>) => {
    if (ctxCurrent) {
      ctxCurrent.beginPath();
      ctxCurrent.moveTo(offsetX, offsetY);
    }
    setDrawing(true);
  };

  const stopDraw = () => {
    if (ctxCurrent) {
      ctxCurrent.closePath();
    }
    setDrawing(false);
  };

  useEffect(() => {
    if (canvasCurrent) {
      canvasCurrent.width = window.innerWidth;
      canvasCurrent.height = window.innerHeight;
    }
  }, []);

  return (
    <canvas onMouseMove={onDraw} onMouseDown={startDraw} onMouseUp={stopDraw} ref={canvasRef} />
  );
};