22.03.03

ujinujin·2022년 3월 3일
0

오늘의 공부

목록 보기
8/8

JavaScript30 Day8주제가 canvas로 그림 그리는 건데 나는 거기에 색깔 선택과 지우개 기능을 추가해봤다.

HTML

<div>
    <label>Color: </label>
    <input type="color">
    <img src="eraser-solid.svg">
  </div>
  <canvas id="draw" width="800" height="800"></canvas>

JS

  const canvas = document.querySelector('#draw');
  const colorPicker = document.querySelector("input");
  const eraser = document.querySelector("img");
  const ctx = canvas.getContext('2d');
  
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  ctx.strokeStyle = colorPicker.value;
  ctx.lineJoin = 'round';
  ctx.lineCap = 'round';
  ctx.lineWidth = 50;

  let isDrawing = false;
  let lastX = 0;
  let lastY = 0;
  let isErasing = false;

  function draw(e) {
    if (!isDrawing) return;
    ctx.beginPath();
    // start from
    ctx.moveTo(lastX, lastY);
    // go to
    ctx.lineTo(e.offsetX, e.offsetY);
    ctx.stroke();
    [lastX, lastY] = [e.offsetX, e.offsetY];
  }

  canvas.addEventListener('mousedown', (e) => {
    isDrawing = true;
    [lastX, lastY] = [e.offsetX, e.offsetY];
  });
  canvas.addEventListener('mousemove', draw);
  canvas.addEventListener('mouseup', () => isDrawing = false);
  canvas.addEventListener('mouseout', () => isDrawing = false);

  function colorUpdate(e) {
    isErasing = false;
    ctx.strokeStyle = e.target.value;
  }
  colorPicker.addEventListener('input', colorUpdate);

  function erasing(e) {
    isErasing = true;
    ctx.strokeStyle = '#fff';
  }
  eraser.addEventListener('click', erasing);

css

html, body {
    margin: 0;
  }
  div {
    padding: 30px;
    background-color: skyblue;
    text-align: center;
    justify-content: center;
  }
  label {
    font-size: 30px;
  }
  input {
    width: 100px;
    height: 30px;
  }
  img {
    width: 30px;
    margin-left: 20px;
    margin-top: 10px;
  }

  img:hover {
    cursor: pointer;
  }

아쉬운 점은 지우개 아이콘 누르면 마우스 커서가 저 아이콘으로 변하게 하려했는데 구현을 못 했다. 커서 아이콘 커스터마이징하는 것을 좀 더 찾아봐야할 것 같다.

profile
백수와 취준생 그 사이 어디

0개의 댓글