본문 바로가기
코딩이야기/JS-그림판 만들기

[JavaScript] - 그림판 만들기 ③ (모드바꾸기⑴)

by TaeHyeon0412 2022. 7. 25.

그리기 모드, 그림 채우기 모드와 전체 배경색 채우기 모드 만들기

html에 버튼을 3개 만들어 준 후 JS에 변수를 선언합니다.
그 후 클릭이벤트 3개를 만들어 줍니다.

1
2
3
4
5
6
7
8
<button class="painting-btn">그리기모드</button>
<button class="painting-fill-btn">그림채우기</button>
<button class="bg-fill-btn">배경채우기</button>
 
 
const paintingBtn = document.querySelector(".painting-btn");
const paintingFillBtn = document.querySelector(".painting-fill-btn");
const bgFillBtn = document.querySelector(".bg-fill-btn");
cs
1
2
3
paintingBtn.addEventListener("click", paintingBtnClick);
paintingFillBtn.addEventListener("click", paintingFillBtnClick);
bgFillBtn.addEventListener("click", bgFillBtnClick);
cs

 

우선 그리기 모드와 그리면 채워지는 모드부터 만듭니다.

마우스 up, down 그리기 이벤트를 만들 때와 같이 업데이트 가능한 let변수를 선언합니다.

let filling = false;

그리기버튼을 클릭하면 filling은 초기값 false를 유지하고
그리면 채워지는 버튼을 누르면 filling이 true가 되게 함수를 만듭니다.

1
2
3
4
5
6
function paintingBtnClick() {
  filling = false;
}
function paintingFillBtnClick() {
  filling = true;
}
cs


그다음 처음 만들었던 mouseup이벤트 함수에 if문을 추가해줍니다.

1
2
3
4
5
6
7
8
9
10
function paintingEnd() {
  if (filling) {      //filling이 true이면
    painting = false//painting은 false로 바꾸고
    ctx.fill();       //ctx를 채운다.
    ctx.beginPath();  //새로운 path 
  } else {
    painting = false;
    ctx.beginPath();
  }
}
cs

 

stoke라는 속성 대신 fill이라는 속성을 추가해주었기 때문에 
color함수에도 fillStyle을 각각 추가해줍니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
function colorChange(event) {
  const colorValue = event.target.value;
  ctx.strokeStyle = colorValue;
  ctx.fillStyle = colorValue;
}
 
function colorClick(event) {
  const colorValue = event.target.dataset.color;
  ctx.fillStyle = colorValue;
  ctx.strokeStyle = colorValue;
  color.value = colorValue;
}
cs

 

 

 

배경 채우기 모드는 간단하게 만들 수 있습니다.
fillRect 메소드로 0,0부터 canvas의 width, height만큼 덮어주면 됩니다. 

1
2
3
function bgFillBtnClick() {
  ctx.fillRect(00, CANVAS_WIDTH, CANVAS_HEIGHT);
}
cs

 

 

3가지 모드 완성!