canvas에 먼지가 비산 하는 것 그려보자.

 

※ 소스

<!DOCTYPE html>
<html lang="kr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <canvas id="canvas1" style="width: 100%; height: 100%"></canvas>
  <script>
    const ctx_size = () => {
      canvas1.width = window.innerWidth - 15;
      canvas1.height = window.innerHeight - 15;
    }
    const rnd = (m, n = 0) => Math.random() * m + n; // 램덤값
    const PI2 = Math.PI * 2; // 360도
    let balls = [];
    const ctx = canvas1.getContext('2d');
    ctx_size();

    // 화면 크기 변하면 캔버스 크기 변경
    window.addEventListener('resize', ctx_size);

    class Ball {
      constructor(x, y) { // 기본 속성들을 정의
        this.x = x;
        this.y = y;
        this.size = rnd(3, 2); // 크기
        this.directionX = rnd(3, 2) * Math.cos(rnd(PI2));
        this.directionY = rnd(3, 2) * Math.sin(rnd(PI2));
        this.color = 'rgba('+rnd(255)+','+rnd(255)+','+rnd(255)+')'; // 공의 색깔
        this.color2 = 'rgba('+rnd(255)+','+rnd(255)+','+rnd(255)+')'; // 공테두리의 색깔
      }

      update() { // 프레임마다 속성들을 변화시킴
        this.y += this.directionY;
        this.x += this.directionX;
        // 바운드 처리
        if(this.y + this.size > ctx.canvas.height || this.y - this.size < 0) {
          this.directionY *= -1;
        }
        if(this.x + this.size > ctx.canvas.width || this.x - this.size < 0 ) {
          this.directionX *= -1;
        }
      }

      draw() { // 그림을 그리기
        ctx.fillStyle= this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, PI2, true);
        ctx.closePath();
        ctx.fill();
        ctx.lineWidth = 1;
        ctx.strokeStyle= this.color2;
        ctx.stroke();
      }
    }
   
    function init(ballNumber) {   // 객체생성
      for(let i = 0; i < ballNumber; i++) {
        balls[i] = new Ball(ctx.canvas.width / 2, ctx.canvas.height / 2);
      }
    }

    function animate(){  // 움직임 그리기
      // 전체 화면 지우기
      ctx.fillStyle='rgba(255, 255, 255, 0.03)';
      ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
      for(i = 0; i < balls.length; i++){
        balls[i].update();
        balls[i].draw();
      }
      requestAnimationFrame(animate);
    }

    init(500); 
    animate(); 
  </script>
</body>
</html>

 

※ 실행화면

728x90

+ Recent posts