Canvas.tsx
1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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>
);
}