본문 바로가기
자바스크립트

[Canvas] Canvas로 비내리는 화면 만들기

by 곰돌찌 2020. 8. 10.

1분코딩님 유투브 캔버스 라이브강좌 들으면서 이래저래 조작해서 만들어보았습니다!

 

<!DOCTYPE html>
<html>
  <head>
    <title>Canvas</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      canvas {
        background: #243c74;
      }
    </style>
  </head>

  <body>
    <h1>Interaction</h1>
    <canvas class="canvas" width="600" height="400"></canvas>

    <script>
      const canvas = document.querySelector('.canvas');
      const context = canvas.getContext('2d');
      const drops = [];
      const mousePos = { x: 0, y: 0 };
      let selectedBox; // 클릭된 box를 넣어놓은 변수

      context.font = 'bold 30px sans-serif';

      class Drop {
        constructor(index, x, y, speed, length) {
          this.index = index;
          this.x = x;
          this.y = y;
          this.speed = speed;
          this.length = length;
          this.draw();
        }

        draw() {
          context.beginPath();
          context.strokeStyle = '#dfdfdf';
          context.moveTo(this.x, this.y);
          context.lineTo(this.x, this.y + this.length);
          context.stroke();
          context.closePath();
        }
      }

      function render() {
        context.clearRect(0, 0, canvas.width, canvas.height);

        drops.forEach((drop) => {
          drop.y += drop.speed;
          if (drop.y > canvas.height) {
            drop.y = 0;
            drop.x = Math.random() * canvas.width;
            drop.speed = Math.random() * 3 + 1;
            drop.length = Math.random() * 5 + 2;
          }

          drop.draw();
        });

        requestAnimationFrame(render); //반복
        //console.log(drops);
      }

      let tempX, tempY, tempSpeed, tempLength;
      for (let i = 0; i < 200; i++) {
        tempX = Math.random() * canvas.width;
        tempY = Math.random() * canvas.height;
        tempSpeed = Math.random() * 3 + 1;
        tempLength = Math.random() * 5 + 2;

        drops.push(new Drop(i, tempX, tempY, tempSpeed, tempLength));
      }
      render();
    </script>
  </body>
</html>

 

See the Pen wvGamZd by alice (@jyynkr92) on CodePen.

댓글