FRONT/JAVASCRIPT

[javascript] 캔버스(Canvas)로 그림판 만들기(3) 색상 채우기-fillRect()

연듀 2021. 6. 25. 14:00

[javascript] 캔버스(Canvas)로 그림판 만들기(1) 캔버스에 선그리기

[javascript] 캔버스(Canvas)로 그림판 만들기(2) 선 색상, 굵기 바꾸기

 

 

 

 

CanvasRenderingContext2D.fillRect()

 

CanvasRenderingContext2D.fillRect()

 

CanvasRenderingContext2D.fillRect() - Web APIs | MDN

The CanvasRenderingContext2D.fillRect() method of the Canvas 2D API draws a rectangle that is filled according to the current fillStyle.

developer.mozilla.org

 

너비  높이에 따라 크기가 결정되는 채워진 사각형을 (x, y) 위치에 그린다. 

 

 

 

 

let filling = false;

function handleModeClick(){
    if(filling === true){
        filling = false;
        mode.innerText = "Fill";
    }else{
        filling = true;
        mode.innerText = "Paint";
    }
    
}

if(mode){
    mode.addEventListener("click", handleModeClick);
}

 

 

디폴트로 filling을 false로 설정해주고, 버튼을 클릭했을 때 paint였으면 fill로, fill이였으면 paint로 바꿔준다.

 

 

 

 

if(canvas){
    canvas.addEventListener("mousemove",onMouseMove);
    canvas.addEventListener("mousedown",startPainting);
    canvas.addEventListener("mouseup", stopPainting);
    canvas.addEventListener("mouseleave", stopPainting);
    canvas.addEventListener("click", handleCanvasClick);
}

 

 

캔버스를 클릭했을 때 handleCanvasClick함수를 실행시키는 addEventListener를 추가한다.

 

function handleCanvasClick(){
    if(filling){
        ctx.fillRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);
    }
}

 

filling이 true일 경우 캔버스를 채워준다.

 

function handleColor(event){
    const color = event.target.style.backgroundColor;
    ctx.strokeStyle = color; //stokeStyle을 override
    ctx.fillStyle = color;
}

 

 

이 때 클릭한 팔레트 색상으로 fillStyle의 색상을 지정해 준다.

 

 

 

=> paint 상태인 버튼을 클릭하면 fill 상태의 버튼이 되고,

색상을 클릭한 후 캔버스의 빈 공간을 클릭하면 선택된 색상으로 캔버스가 채워진다.