Canvas로 선을 그리고 그 여러개의 선들을 각각 편집하기 위해서는 선들을 선택하는 동작이 필요하다.
이를 위해서는 각각의 선(후에 도형, 글씨, 이미지)을 새로운 Canvas에 그려주고 Canvas를 선택하여 처리해야한다.
먼저 선의 모든 path정보를 저장하는 배열을 생성한 뒤
/* main_canvas */
path.forEach((pos) => {
if (pos[0] > max_x) max_x = pos[0];
if (pos[0] < min_x) min_x = pos[0];
if (pos[1] > max_y) max_y = pos[1];
if (pos[1] < min_y) min_y = pos[1];
});
const newElement: DrawElement = {
left: min_x,
top: min_y,
width: max_x - min_x,
height: max_y - min_y,
imageData: context.getImageData(min_x, min_y, max_x - min_x, max_y - min_y),
};
현재 canvas의 영역 내 선이 그려진 영역을 image로 저장한다. 해당 정보를 새로운 canvas에 넘겨준다.
/* line_canvas */
const image = new Image();
image.width = lineElement.width;
image.height = lineElement.height;
canvasRef.current.width = lineElement.width;
canvasRef.current.height = lineElement.height;
canvasRef.current.style.backgroundColor = color;
context.putImageData(lineElement.imageData, 0, 0);
canvasRef.current.style.transform = `translate(${lineElement.left}px, ${lineElement.top}px)`;
새로운 Canvas의 크기를 넘겨받은 image의 크기와 일치시키고 이미지를 0, 0 좌표에서 그려준다.
그리고 마지막으로 image가 그려진 위치로 transform시켜주면 그려줬던 똑같은 위치에서 새로운 Canvas에 그려진 image를 확인할 수 있다.
다음으론 핵심기능인 각각의 Canvas를 picking하는 기능을 구현할 예정이다.
'👨💻 javascript' 카테고리의 다른 글
Chorme Extensions 업비트 (0) | 2024.02.26 |
---|---|
[React로 화이트보드] Canvas Color Picking + 선택된 요소 변형 동시에 적용하기 (0) | 2024.02.05 |
[React로 화이트보드] 마우스를 이용한 자연스러운 Rotate, Scale 구현하기 (0) | 2024.02.05 |
[React로 화이트보드] Picking Element Transform issue (0) | 2024.02.04 |
[React로 화이트보드] Draw Element Picking 구현 (2) | 2024.01.10 |