Notice
Recent Posts
Recent Comments
Link
관리 메뉴

윤일무이

[노마드코더 바닐라JS로 그림 앱 만들기] #2 Painting Board (1) 본문

👋🏻 JavaScript/💭 노마드코더 바닐라JS

[노마드코더 바닐라JS로 그림 앱 만들기] #2 Painting Board (1)

썸머몽 2023. 3. 21. 18:07
728x90

📌  마우스로 점을 찍자

캔버스 안에 마우스로 점을 찍을 때, 그 위치에 점이 찍히게 하고 싶다.

우선 캔버스 안에 점을 찍을 위치를 뽑아주어야 한다. 그 위치는 offsetX, offsetY이다.

 

점의 크기를 정해주고 사용할 색을 담은 어레이를 만들어주었다.

캔버스에 클릭이라는 이벤트가 일어날 때 cursor_move라는 함수가 작동하는데,

해당 함수는 이벤트가 발생한(클릭한) 위치의 offsetX, offsetY을 좌표로 사용한다.

 

참고로 매 좌표마다 패스를 새로 시작하게 설정해주어야 한다. 그렇지 않으면 점을 찍을 때마다 안 떨어지고 달라 붙는다.

점을 찍을 때마다 원이 찍힐 것이고, 그 원의 좌표는 아까 지정한 좌표 + 반지름 크기 10 + 원의 모양으로 arc를 정해준다.

컬러의 경우 이전에 배웠던 랜덤을 활용하여 점을 찍을 때마다 랜덤의 컬러가 나오게끔 해주었다. 

ctx.fill을 까먹으면 아무 것도 안 나오니 주의.

 

Hi

 

ctx.lineWidth = 2;

const colors = [
    "red",
    "orange",
    "yellow",
    "green",
    "blue",
    "navy",
    "purple"
]

function cursor_move(event) {
    let x = event.offsetX;
    let y = event.offsetY;
    ctx.beginPath();
    ctx.arc(x, y, 10, 0, 2*Math.PI);
    const color = colors[Math.floor(Math.random() * colors.length)];
    ctx.fillStyle = color;
    ctx.fill();
}

canvas.addEventListener("click", cursor_move);

 

 

📌  드래그 하는 대로 나타나게 해보자

단순히 클릭할 때만이 아니라 마우스를 꾸욱 누르고 있을 때 캔버스 위에 흔적이 남고, 마우스를 뗐을 때 멈추게 해보자.

이런 기능들은 mousemove, mousedown, mouseup, mouseleave 등의 이벤트를 활용해야 한다.

isPainting 이라는 변수를 설정했고 이 변수가 true, false일 때 작동하는 함수들로 그림을 그린다.

 

1) 캔버스 위에 mousedown (꾹 누른 것)이 발생하면 함수 startPainting이 작동한다. 

-함수 startPainting는 isPainting을 true로 설정한다.

 

2) 캔버스 위에서 마우스가 움직일 때 1번의 경우면 그림이 그려져야 한다. 꾹 누르지 않은 채 그냥 위에 올라온 거라면 그려지면 안되니까.

-따라서 isPainting가 true일 때 ctx.lineTo는 이벤트가 발생한 좌표 (꾹 누른 곳)에서부터 그림이 그려져야 한다. 

-ctx.moveTo를 해주지 않으면 그리고 멈췄을 때 그 멈춘 좌표에서 이어져서 그림이 그려진다.

 

3) 마우스를 떼거나 캔버스에서 떠난 경우에는 그림이 그려지지 않아야 한다.

-mouseup, mouseleave일 때는 cancelPainting이라는 함수로 isPainting를 false로 만들어주면 된다.

-이러면 mousedown 외의 경우에 그림이 그려지지 않는다.

 

let isPainting = false;

function onMove(event) {
    if (isPainting) {
        ctx.lineTo(event.offsetX, event.offsetY);
        ctx.stroke();
        return;
    }
    ctx.moveTo(event.offsetX, event.offsetY);
}

function startPainting() {
    isPainting = true;

}

function cancelPainting() {
    isPainting = false;

}

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

 

📌  선의 굵기를 바꿔보자

input type range를 사용해 최소값1, 최대값10, 기본값5, 간격0.5을 주었다.

JS에서도 불러와서 이 range의 값이 ctx의 lineWidth가 되게 설정해주었다.

range의 값이 change될 때마다 반영되어야 하기 때문에 event를 매개변수로 이벤트리스너를 써주었다.

여기서 event target은 range다.

 

<body>
    <canvas></canvas>
    <input id="line-width" type="range" min="1" max="10" value="5" step="0.5">
    <script src="app.js"></script>
</body>
const lineWidth = document.getElementById("line-width");
ctx.lineWidth = lineWidth.value;

function onLineWidthChange(event) {
    ctx.lineWidth = event.target.value;
}

lineWidth.addEventListener("change", onLineWidthChange);

 

📌  색을 정하고 그에 맞게 바꿔보자

input type color를 사용해 컬러 팔레트를 불러온다. (진짜 팔레트는 아니고 그냥 단색 뽑는 팔레트)

JS에서도 불러온 후, 이 color에서 change가 일어나면 함수 onColorChange가 작동되게 한다.

이 함수는 event(change)를 매개변수로 사용했고, fill이든 stroke든 상관없이 색을 입혀준다.

이러면 이제 정한 색대로 선이든 색이든 표현된다.

 

    <input type="color" id="color">
const color = document.getElementById("color");

function onColorChange(event) {
    ctx.strokeStyle = event.target.value;
    ctx.fillStyle = event.target.value;
}

color.addEventListener("change", onColorChange);
728x90