React에서 Canvas를 써보자

maru5mango·2022년 3월 16일
2

After9

목록 보기
1/3

첫번째 과제

가장 첫번째 과제로는 파워 포인트같이 도형을 선택하고 그리는 작업을 해보려고 한다. 그런데 Canvas도 써봤고, React도 써봤지만 그 둘을 같이 써본적이 없어서 일단 간단한 프로젝트를 만들 예정이다.

  • canvas는 DOM을 직접 다루는데 React는 virtualDom에 등록해서 dom을 관리하다보니 먼저 React에서 Canvas를 쓰는 Best Practice를 알고 싶었다.

1) canvas에 Ref를 적용해 Element 가져오기
2) 컴포넌트의 state 변화로 React가 re-rendering 할 수 있도록 등록

보통 이런 방식으로 사용하는 것 같다.

step 1. canvas Ref

  • canvas에 useRef를 이용하여 canvas HTML Element를 연결한다.
const canvasRef = useRef<HTMLCanvasElement>(null);

...

return(
  <div>
    <canvas ref={canvasRef} />
  </div>
);

step 2. canvas 이용하기

const canvas: HTMLCanvasElement = canvasRef.current;
const ctx = canvas.getContext("2d");
if (context) {
      //캔버스 다루기
}

example) canvas 내에서 마우스 클릭하면 해당 좌표 구하기

  • App.tsx
import * as React from 'react'
import './App.css';

interface Coordinate {
  x: number | null;
  y: number | null;
}

export default function App(){
  const canvasRef = React.useRef<HTMLCanvasElement>(null);
  const [mousePoint, setMousePoint] = React.useState<Coordinate>({
    x: null,
    y: null
  });
  
  
  const getCurrentPoint = (event: MouseEvent): Coordinate => {
    if (!canvasRef.current) {
      return;
    }
    const canvas: HTMLCanvasElement = canvasRef.current;
    return {
      x: event.pageX - canvas.offsetLeft,
      y: event.pageY - canvas.offsetTop,
    };
  };
  
  const logCurrentPoint = (event: MouseEvent) => {
  	const newPoint = getCurrentPoint(event);
    setMousePoint(newPoint);
  }
  
  return(
    <div>
      <canvas ref={canvasRef} width={400} height={600} className="canvas" onClick={(e) => logCurrentPoint(e)}/>
      <div>
        <h2>x: {mousePoint.x}</h2>
        <h2>y: {mousePoint.y}</h2>
      </div>
    </div>
  );
}
  • App.css
main {
  text-align: center;
  vertical-align: center;
  line-height: 100vh
}

.canvas {
  border :3px solid black;
}

다음 시간에는 도형을 선택하고 canvas에 그려보는 작업을 할 예정이다.

0개의 댓글