FRONT/JAVASCRIPT

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

연듀 2021. 6. 20. 11:06

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D

 

CanvasRenderingContext2D - Web APIs | MDN

The CanvasRenderingContext2D interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of a

element. It is used for drawing shapes, text, images, and other objects.

developer.mozilla.org

 

 

canvas는 context를 갖고있는 html의 요소로, 그 안에서 픽셀들을 다룬다.

 

 

 

CanvasRenderingContext2D인터페이스의 캔버스 API는 2차원의 다양한 개체를 그리는데 사용된다.

 

 

 <canvas id="jsCanvas" class="canvas"></canvas>

canvas를 작업할 HTML요소를 만든다.

 

 

 

const canvas = document.getElementById("jsCanvas");
const ctx = canvas.getContext("2d");

 

2D 렌더링 context를 얻기 위해, "2d"를 전달인수로 받아 getContext함수를 호출한다.

 

 

 

canvas.width = 700;
canvas.height = 700;

ctx.strokeStyle = "#2c2c2c";
ctx.lineWidth = 2.5;

 

캔버스 크기와 디폴트 값들을 설정해준다. 

fillStyle - 색상이나 스타일을 도형안에 사용할 수 있다.

strokeStyle - 색상이나 스타일을 라인에 사용할 수 있다.

linewidth - 선의 굵기를 지정한다.

 

여기선 strokeStyle으로 색상을 검정색으로 설정하고, linewidth를 2.5로 해주었다.

 

 

 

https://developer.mozilla.org/en-US/docs/Web/API/Path2D

 

Path2D - Web APIs | MDN

The Path2D interface of the Canvas 2D API is used to declare a path that can then be used on a CanvasRenderingContext2D object. The path methods of the CanvasRenderingContext2D interface are also present on this interface, which gives you the convenience o

developer.mozilla.org

 

 

 

path를 만드는건 기본적으로 선(line), 선의 시작점을 만드는 것이다.

 

painting을 할 땐 path를 그리는게 필요하지 않는다.

painting을 하지 않을 때에만 path를 그리는게 필요하다.

 

시작점은 마우스가 움직이는 곳이라면 어디든지 된다.

그러다 클릭하면 시작점부터 클릭한 곳까지 선을 만든다.

 

function onMouseMove(event){ //모든 움직임을 감지하고 line을 만드는 함수
     //스크린과 캠퍼스가 크기가 다른 경우 offsetX와 offsetY를 사용한다.
    const x = event.offsetX;
    const y = event.offsetY;
    if(!painting){
        ctx.beginPath(); //path를 만듬
        ctx.moveTo(x, y); //x, y 좌표로 옮김
    }else{
        ctx.lineTo(x, y);
        ctx.stroke();
    }
}

 

 

 

마우스를 움직이면서 path를 만들고, 마우스가 가는 곳으로 path를 옮긴다.

클릭하면 path의 끝나는 지점으로서 클릭한 위치가 선택된다.

 

.lineTo() : 현재 sub-path의 마지막 점을 특정 좌표와 직선으로 연결한다.

.stroke() : 현재의 stroke style로 현재의 sub-path에 획을 긋는다.

 

 

 


전체 코드

 

app.js

const canvas = document.getElementById("jsCanvas");
const ctx = canvas.getContext("2d");

canvas.width = 700;
canvas.height = 700;

ctx.strokeStyle = "#2c2c2c";
ctx.lineWidth = 2.5;

let painting = false;

function stopPainting(event){
    painting = false;
}

function startPainting(){
    painting = true;
}

function onMouseMove(event){ //모든 움직임을 감지하고 line을 만든다.
     //스크린과 캠퍼스가 크기가 다른 경우 offsetX와 offsetY를 사용한다.
    const x = event.offsetX;
    const y = event.offsetY;
    if(!painting){
        ctx.beginPath(); //path를 만듬
        ctx.moveTo(x, y); //x, y로 옮김
    }else{
        ctx.lineTo(x, y);
        ctx.stroke();
    }
}

function onMouseDown(event){
    painting = true;
} 



if(canvas){
    canvas.addEventListener("mousemove",onMouseMove);
    //캔버스 안에서의 움직임 감지
    canvas.addEventListener("mousedown",startPainting);
    //클릭했을때 발생하는 event
    canvas.addEventListener("mouseup", stopPainting);
    canvas.addEventListener("mouseleave", stopPainting);
   
}

 

 

클릭하지 않은 상태로 마우스를 움직였을 때는 path를 시작한다.(beginPath)

(path는 선이다.)

path를 만들면 마우스의 x y 좌표로 path를 옮긴다(moveTo)

클릭하면(mousedown) startPainting 함수가 실행돼 painting 값이 true가 된다.

onMouseMove 함수에서 만약 painting을 하고있다면 path의 이전 위치에서 지금 위치까지 선을 만들어(lineTo)

획을 그려준다.(stroke)

 

 


 

 

정리

 

 

ctx.beginPath(); //경로 생성
ctx.moveTo(x, y); //선 시작 좌표
ctx.lineTo(x, y); //선 끝 좌표
ctx.stroke(); //선 그리기