Canvas.tsx 1.08 KB
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Vector } from './types';

export const Canvas: React.FC = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  const getCoordinates = useCallback((event: MouseEvent): Vector | undefined => {
    if (!canvasRef.current) {
      return;
    } else {
      return {
        x: event.pageX - canvasRef.current.offsetLeft,
        y: event.pageY - canvasRef.current.offsetTop
      };
    }
  }, []);

  const drawLine = useCallback((prev: Vector, current: Vector) => {
    if (canvasRef.current) {
      const context = canvasRef.current!.getContext('2d');
      if (context) {
        context.strokeStyle = 'black';
        context.lineJoin = 'round';
        context.lineWidth = 5;

        context.beginPath();
        context.moveTo(prev.x, prev.y);
        context.lineTo(current.x, current.y);
        context.closePath();

        context.stroke();
      }
    }
  }, []);

  return (
    <div className='mx-3 px-2 py-1 rounded shadow'>
      <canvas ref={canvasRef} width='512' height='384' />
    </div>
  );
}