Fun with HTML5 Canvas

위풍당당수·2023년 12월 18일
0

Javascript30

목록 보기
8/10

코드

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>HTML5 Canvas</title>
    <link rel="icon" href="https://fav.farm/🔥" />
  </head>
  <body>
    <canvas id="draw" width="800" height="800"></canvas>
    <script>
      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; //마우스다운 상태가 아니면 함수 이탈
        console.log(e);
        ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
        ctx.beginPath();
        // start from
        ctx.moveTo(lastX, lastY);
        // go to
        ctx.lineTo(e.offsetX, e.offsetY);
        ctx.stroke();
        [lastX, lastY] = [e.offsetX, e.offsetY];

        //hue 값 조정
        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);
      canvas.addEventListener("mouseup", () => (isDrawing = false));
      canvas.addEventListener("mouseout", () => (isDrawing = false));
    </script>

    <style>
      html,
      body {
        margin: 0;
      }
    </style>
  </body>
</html>

결과

profile
가장 어려워 하는 '기록'하기

0개의 댓글