클래스룸페이지
ᄂ콘텐츠올리기
ᄂ콘텐츠삭제
ᄂ콘텐츠순서변경
ᄂ콘텐츠수정
ᄂ콘텐츠확인(시청)
ᄂ커뮤니티연동
Typescript, Next.js (13v), tailwindCSS
import React, { useState, useRef, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { lines } from '../redux_toolkit/drawingSlice';
const drawLine = (context, line) => {
context.beginPath();
context.moveTo(line.start.x, line.start.y);
context.lineTo(line.end.x, line.end.y);
context.strokeStyle = line.color;
context.stroke();
}
const DrawingBoard = () => {
const dispatch = useDispatch();
const currentColor = useSelector((state) => state.drawing.currentColor);
const [drawing, setDrawing] = useState(false);
const [linesDrawn, setLinesDrawn] = useState([]);
const canvasRef = useRef();
const handleMouseEvents = (event) => {
const rect = canvasRef.current.getBoundingClientRect();
const point = {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
if (event.type === 'mousedown') {
setDrawing(true);
setLinesDrawn([...linesDrawn, { start: point, end: point, color: currentColor }]);
} else if (event.type === 'mouseup' && drawing) {
setDrawing(false);
dispatch(lines(linesDrawn[linesDrawn.length - 1]));
} else if (event.type === 'mousemove' && drawing) {
setLinesDrawn(linesDrawn.slice(0, -1).concat({ ...linesDrawn[linesDrawn.length - 1], end: point }));
}
};
useEffect(() => {
const context = canvasRef.current.getContext('2d');
context.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
linesDrawn.forEach(line => drawLine(context, line));
}, [linesDrawn]);
return (
<canvas
ref={canvasRef}
width="500"
height="500"
onMouseDown={handleMouseEvents}
onMouseUp={handleMouseEvents}
onMouseMove={handleMouseEvents}
style={{ cursor: 'crosshair', border: '1px solid black' }}
/>
);
};
export default DrawingBoard;
- 마우스를 누르면 (mousedown 이벤트) 그리기를 시작
- 새로운 선을 linesDrawn 배열에 추가.
- 마우스를 떼면 (mouseup 이벤트) 그리기를 중단.
- 그림의 현재 상태를 Redux store에 dispatch.
- 마우스를 움직이면 (mousemove 이벤트) 그리는 도중이라면 마지막 선의 끝점을 업데이트
본 후기는 유데미-스나이퍼팩토리 10주 완성 프로젝트캠프 학습 일지 후기로 작성 되었습니다.
#프로젝트캠프 #프로젝트캠프후기 #유데미 #스나이퍼팩토리 #웅진씽크빅 #인사이드아웃 #IT개발캠프 #개발자부트캠프 #리액트 #react #부트캠프 #리액트캠프