Coding Archive

canvas js로 구현하기 (2) - 그리기 함수 만들기 본문

💻 Programming/Java Script

canvas js로 구현하기 (2) - 그리기 함수 만들기

코등어 2022. 9. 29. 16:09

canvas js로 구현하기

 

 

앞서 배운 내용을 바탕으로 js에서 그리기 함수를 만들어 canvas를 구현해 보았습니다.

 

 

 

· html / css

 

html에서 id가 canvas인 canvas 태그를 생성합니다.

 

1
<canvas id="canvas"></canvas>
cs

 

원하는 디자인대로 css를 작성합니다.

 

1
2
3
4
5
6
7
8
#canvas {
  height: 700px;
  width: 1000px;
  background-color: white;
  border-radius: 50px;
  box-shadow: var(--box-shadow);
  margin: 0 30px;
}
cs

 

 

 

 

 

· js

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
const lineWidth = document.querySelector(".lineWidth");
 
const CANVAS_WIDTH = 1000;
const CANVAS_HEIGHT = 700;
 
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
 
ctx.lineWidth = lineWidth.value;
ctx.lineCap = "round";
ctx.strokestyle = "black";
 
ctx.beginPath();
ctx.moveTo(00);
ctx.lineTo(400600);
ctx.stroke();
cs

 

 

여기까지 선이 문제없이 잘 나오는 것을 확인할 수 있습니다.

 

 


 

이제 그리기 함수를 만들어 보겠습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
const lineWidth = document.querySelector(".lineWidth");
 
const CANVAS_WIDTH = 1000;
const CANVAS_HEIGHT = 700;
 
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
 
ctx.lineWidth = lineWidth.value;
ctx.lineCap = "round";
ctx.strokestyle = "black";
 
// 기본상태는 false
let painting = false;
 
// !painting은 !false(true)를 의미하면서 if(true){}처럼 if문을 실행하게 된다. 
// if(trud)일 때는 경로를 만들고, else 상황일 때 선이 canvas에 그려지게 된다.
function onMouseMove(event) {
  if (!painting) {
    ctx.beginPath();
    ctx.moveTo(event.offsetX, event.offsetY);
  } else {
    ctx.lineTo(event.offsetX, event.offsetY);
    ctx.stroke();
  }
}
 
function startPainting() {
  painting = true;
}
 
function stopPainting() {
  painting = false;
}
 
canvas.addEventListener("mousemove", onMouseMove);
canvas.addEventListener("mousedown", startPainting);
canvas.addEventListener("mouseup", stopPainting);
canvas.addEventListener("mouseleave", stopPainting);
cs

 

path는 canvas 안에서 마우스를 움직이는 동안 좌표를 만들고 있지만, 클릭 전까지 painting은 false이므로 보이지 않습니다.

painting의 기본 값은 false이고, 마우스가 클릭되면 startPainting()을 통해 true가 됩니다. 그렇기 때문에 !painting은 false이고, else 안의 lineTo()와 stroke()를 통해 선이 그려지게 됩니다.

 

 

최종적으로 canvas가 구현되는 걸 확인할 수 있었습니다.

 

 

Comments