본문 바로가기

자바스크립트/DOM 예제

자바스크립트 그림 그리기 - canvas

<canvas id="canvas"></canvas>

<button id="saveButton">save</button>

 

1. 그리기 기능

 

// 초기값

const canvas = document.getElementById('canvas');

const context = canvas.getContext('2d');

canvas.width = 500;

canvas.height = 500;

context.strokeStyle = 'black';

context.lineWidth = 1;

 

// path를 생성했는지 여부

let hasPath = false;

 

function onMouseMove(event) {

    const x = event.offsetX;

    const y = event.offsetY;

    if(!hasPath) {

        // path 생성

        context.beginPath();

        // path의 좌표 지정

        context.moveTo(x, y);

        hasPath = true;

    } else {

        // path의 이전 좌표와 지금 좌표를 선으로 연결한다.

        context.lineTo(x ,y);

        // stroke를 그린다.

        context.stroke();

    }

}

 

function onMouseOut() {

    // path 닫음

    context.closePath();

    hasPath = false;

}

 

canvas.addEventListener('mousemove', onMouseMove);

canvas.addEventListener('mouseout', onMouseOut);

 

2. 그림 저장 기능

 

function clickSaveButton() {

    // canvas에 그려진 이미지를 만들어서 URL로 보낸다.

    const image = canvas.toDataURL();

    // a 엘리먼트를 가상으로 만들어서 href 속성에 URL의 링크를 넣고

    const link = document.createElement('a');

    link.href = image;

    // download 속성을 넣어서 클릭했을 때 URL에 위치한 것을 다운 받게 한다.

    link.download = 'imageFile';

    // a 엘리먼트를 클릭한다.

    link.click();

}

 

const saveButton = document.getElementById('saveButton');

saveButton.addEventListener('click', clickSaveButton);