<canvas width="300" height="300"></canvas>

<div class="buttons">
  <div class="clear">지우기</div>
  <div class="download">다운로드</div>
</div>

<p>그림을 그려보세요!</p>
canvas {
  background: #fff;
  border: 4px solid #444;
}

.buttons {
  width: 308px;
  display: flex;
  justify-content: space-between;
}

.buttons > div {
  width: 48%;
  padding: .6rem 1.5rem;
  font-size: 1rem;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.buttons > div:nth-child(1) {
  background: #f03d3d;
}

.buttons > div:nth-child(2) {
  background: #febf00;
}

@import url("https://cdn.jsdelivr.net/gh/orioncactus/pretendard/dist/web/static/pretendard.css");

* {
  box-sizing: border-box;  
  font-family: Pretendard;
}

p {
  position: absolute;
  top: 154px;
  left: 154px;
  transform: translate(-50%, -50%);
  opacity: .3;
  pointer-events: none;
}
const $canvas = document.querySelector("canvas");
const ctx = $canvas.getContext("2d");

// 캔버스 다운로드
const download = () => {
  const $link = document.createElement("a");
  
  $link.download = "canvas.png";
  $link.href = $canvas.toDataURL("image/png");
  
  $link.click();
}

// -----------------------
// 그림판 그리기
let prevPos = [];

const draw = (x, y) => {
  ctx.lineWidth = 3;
  ctx.lineCap = "round";
  ctx.lineJoin = "round";
  
  ctx.beginPath();
  ctx.moveTo(...prevPos);
  ctx.lineTo(x, y);
  ctx.stroke();
  ctx.closePath();
  
  prevPos = [x, y];
}

$canvas.onmousedown = (e) => {
  prevPos = [e.offsetX, e.offsetY];
  
  $canvas.onmousemove = (e) => draw(e.offsetX, e.offsetY);
}

$canvas.onmouseup = () => {
  $canvas.onmousemove = false;
}

$canvas.onmouseleave = () => {
  $canvas.onmousemove = false;
}

document.querySelector(".clear").onclick = () => {
  ctx.clearRect(0, 0, 300, 300);
}

document.querySelector(".download").onclick = () => {
  download();
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.