Coding Archive

canvas js로 구현하기 (3) - canvas drawing mode변경하기(fill/draw) 본문

💻 Programming/Java Script

canvas js로 구현하기 (3) - canvas drawing mode변경하기(fill/draw)

코등어 2022. 10. 1. 11:12

canvas drawing mode변경하기(fill/draw)

 

기본 상태는 draw 상태지만 fill 버튼을 누르면 canvas에 색을 채울 수 있도록 만들어 봤습니다.

 

 

 

 

 

1 .   html 요소 선택, 접근하기

 

1
const modeBtn = document.querySelector(".modeBtn");
cs

 

querySelector를 사용해 원하는 html 요소를 찾습니다.

 

 

 

 

 

2 .  버튼에 클릭 이벤트 주기 / 모드 변환 함수 구현하기

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const modeBtn = document.querySelector(".modeBtn");
 
let filling = false;
 
function onModeClick() {
  if (!filling) {
    filling = true;
    modeBtn.innerText = "draw";
    canvas.addEventListener("click", fillPainting);
  } else {
    filling = false;
    modeBtn.innerText = "fill";
  }
}
 
modeBtn.addEventListener("click", onModeClick);
cs

 

기본 상태는 filling = false 상태로 설정해 두고, modeBtn에 addEventListener를 줍니다.

그리고 filling이 true일 때 innerText가 draw로 바뀌고, canvas를 클릭했을 때 색이 채워지도록 합니다. (fill 모드)

filling이 false일 때는 innerText가 fill로 바뀝니다. (draw 모드)

 

 

 

 

 

3 .  색 채우기 함수 구현하기

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const modeBtn = document.querySelector(".modeBtn");
 
let filling = false;
 
function fillPainting() {
  ctx.fillRect(00, CANVAS_WIDTH, CANVAS_HEIGHT);
}
 
function onModeClick() {
  if (!filling) {
    filling = true;
    modeBtn.innerText = "draw";
    canvas.addEventListener("click", fillPainting);
  } else {
    filling = false;
    modeBtn.innerText = "fill";
  }
}
 
modeBtn.addEventListener("click", onModeClick);
 
cs

 

ctx.fillRect()를 사용해 캔버스 시작점과 크기를 설정해 색을 채우도록 만들어 줍니다.

ctx.fillRect(x, y, width, height) -> width와 height에 의해 결정된 사이즈로 (x, y)위치에 색칠된 사각형을 그립니다.

 

 

 


 

 

 

 

하지만 여기까지 했을 때 fill모드로 전환하고 색을 채우고 난 후, 다시 draw모드로 전환하여 그려보면 계속 색이 채워지는 문제가 발생했습니다.

 

 

1
2
3
4
5
function fillPainting() {
  if (filling) {
    ctx.fillRect(00, CANVAS_WIDTH, CANVAS_HEIGHT);
  }
}
cs

 

이렇게 조건문을 사용하니 문제는 해결됐습니다.

if 조건문은 지정한 조건이 참인 경우 명령문(statement)을 실행합니다. 

fill모드일 때  addEventListener가 들어가 있으니까 위의 함수에 조건문이 필요하지 않을 거라 생각했는데

filling이 true일 때만 실행하라는 조건을 사용하니 fill모드 일 때만 색이 채워지는 것을 확인할 수 있었습니다.

 

+

추가적으로 

canvas.addEventListener("click", fillPainting); 를 조건문 밖으로 빼도 문제없이 작동했습니다.

 

Comments