본문 바로가기
Study/Vanila JS

[노마드코더] 바닐라 JS로 그림 만들기 - mouse painting

by 22정민 2023. 9. 26.

https://nomadcoders.co/javascript-for-beginners-2

 

바닐라JS로 그림 앱 만들기 – 노마드 코더 Nomad Coders

Build a Meme Maker

nomadcoders.co

그림판 구현

1. canvas위에 마우스를 올림

2. 마우스가 있는 곳으로 브러쉬를 움직임(moveTo)

3. 마우스를 누르면 isPainting이 true로(mousedown)

4. 마우스를 누른 채로 움직인다면, 마우스를 누른 곳에서 움직이는 쪽으로 선을 그림 -> 그 선을 stroke 해줌

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 600;
ctx.lineWidth = 2;

let isPainting = false;

function onMove(event) {
  //선 그리기
  if (isPainting) {
    ctx.lineTo(event.offsetX, event.offsetY);
    ctx.stroke();
    return;
  }
  //브러쉬 움직이기
  ctx.moveTo(event.offsetX, event.offsetY);
}
function onMouseDown() {
  isPainting = true;
}
function onMouseUp() {
  isPainting = false;
}

canvas.addEventListener("mousemove", onMove);
canvas.addEventListener("mousedown", onMouseDown);
canvas.addEventListener("mouseup", onMouseUp);

- mousedown : 마우스를 누른 채로 있는 상태

- isPainting이 true일 때는 stroke를 써서 선을 그리고, false일 때는 움직이기만 하게 해줌

-> 자유로운 그리기 가능

 

 

 

 

 

 

 

 

버그 수정

- 문제점 : 마우스를 누른 상태로 canvas의 바깥까지 선을 그린 후 마우스를 땐 상태에서 다시 canvas로 들어가면 선이 그려짐

- 원인 : mouseup 이벤트가 실행되지 않았기 때문

- 해결 방법 : 마우스가 떠났을 때를 감지(mouseleave)

//생략
function startPainting() {
  isPainting = true;
}
function cancelPainting() {
  isPainting = false;
}

canvas.addEventListener("mousemove", onMove);
canvas.addEventListener("mousedown", startPainting);
canvas.addEventListener("mouseup", cancelPainting);
canvas.addEventListener("mouseleave", cancelPainting);