자바스크립트 - 그림판 (다양한 버튼 기능 만들기)

Jin Yun·2023년 9월 30일
0

그림판에 다양한 기능을 가진 버튼을 만들어본다. 우리가 그림판을 사용하다보면 그림을 한꺼번에 지울수도 있고 지우개 기능도 있고 그림판을 같은 색으로 꽉채울수도 있을 것이다.

1. Fill & Draw Button

1. HTML에 Fill button 을 만들어준다. 
  <button id="mode-btn">Fill</button>
  1. JS에 modeBtn을 가져오고 click 이벤트리스너를 추가한다.
const modeBtn = document.getElementById("mode-btn")
modeBtn.addEventListener("click", onModeClick);
  1. onModeClick function 을 만든다. 만약 유저가 버튼을 클릭했을때 fillingMode가 true라면 false로 바꾸고 innerText를 fill로 바꾸고 false 경우 fillingMode를 true로 바꾸고 innerText를 Draw로 한다.
function onModeClick () {
 if (fillingMode) {
    fillingMode = false;
    modeBtn.innerText = "Fill";
 } else {
    fillingMode = true;
    modeBtn.innerText = "Draw";
 }
}
  1. 또한 캔버스를 클릭할 경우 fillingMode가 true라면 선택한 색상으로 canvas가 가득차게 한다.
function onCanvasClick () {
    if (fillingMode) {
        ctx.fillRect(0,0,CANVAS_HEIGHT,CANVAS_WIDTH);
    }
}

2. Destroy & Erase Button

  1. 위와 같은 형태로 HTML에 각각 Destroy와 Erase Button을 만들어준다.
 <button id="destroy-btn">Destroy</button>
 <button id="eraser-btn">Eraser</button>
  1. 각각 버튼에 click 이벤트리스너를 추가 해준뒤 DestoryBtnClick에서는 fillStyle 을 white로 변경하고 캔버스가 흰색으로 변경되게 한다. Erase버튼에서는 strokeStyle을 white로 변경한뒤 modeBtn을 Fill로 변경하고 fillingMode를 false로 한다. 이렇게 안하면 fillingMode일때는 전체 화면이 흰색으로 변할수도 있다.
function onDestroyBtnClick () {
   ctx.fillStyle = "white";
   ctx.fillRect(0,0,CANVAS_HEIGHT,CANVAS_WIDTH);
}


function onEraseBtnClick () {
    ctx.strokeStyle = "white";
    modeBtn.innerText = "Fill";
    fillingMode = false;
}
profile
호주 개발자

0개의 댓글

관련 채용 정보