# Canvas Draw

{% tabs %}
{% tab title="JavaScript" %}

```javascript
// 캔버스에 그림그리기 
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.strokeStyle = '#BADA55'; 
ctx.lineJoin = 'round'; // 선이 꺽이는 부분의 스타일 지정
ctx.lineCap = 'round';  // 선 끝 부분의 스타일 지정
ctx.lineWidth = 100;
// ctx.globalCompositeOperation = 'multiply';

let isDrawing = false; // 그림을 그린후에 마우스를 땠을때 멈춰야하므로 
let lastX = 0;
let lastY = 0;
let hue = 0;
let direction = true;

function draw(e) {
  if (!isDrawing) return; // mouse down 아니면 함수실행을 멈춰라 
  ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;// 도형의 윤곽선 색을 설정
  ctx.beginPath();  // 캔버스를 시작할 때 새로운 path를 만들기 위해 사용
  // start from
  ctx.moveTo(lastX, lastY);
  // go to
  ctx.lineTo(e.offsetX, e.offsetY);    //e.offsetX, e.offsetY 마우스 이동에 따라 EventListener를 걸어 놓은 이벤트 객체 -> 마우스 위치를 반환 하고 draw 함수에서 이를 사용
  ctx.stroke(); // 윤곽선을 이용하여 도형을 그리는 함수
  [lastX, lastY] = [e.offsetX, e.offsetY]; 

  hue++;
  if (hue >= 360) {
    hue = 0;
  }
  if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) {
    direction = !direction;
  }

  if(direction) {
    ctx.lineWidth++;
  } else {
    ctx.lineWidth--;
  }

}

canvas.addEventListener('mousedown', (e) => {   //이벤트리스너를 추가
  isDrawing = true;
  [lastX, lastY] = [e.offsetX, e.offsetY];
});


canvas.addEventListener('mousemove', draw); // 마우스가 움직일때 draw 함수 실행
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);

canvas.addEventListener("mousedown", (e) => {
    if (e.which === 1) {
      isDrawing = true;
      [lastX, lastY] = [e.offsetX, e.offsetY];
    } else if (e.which === 3) {
// canvas 지우는 부분
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
  });

```

{% endtab %}

{% tab title="HTML" %}

```markup
<canvas id="draw" width="100%" height="100vh"></canvas>
```

{% endtab %}
{% endtabs %}

![](/files/-Md0iNZB3UgrQJB7pTVX)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://leeboa.gitbook.io/study/javascript30/canvas-draw.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
