[JS] Circles on Canvas

김종상·2023년 3월 28일
0

FrontEnd

목록 보기
1/4
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Chrome Dinosaur Game</title>
    <style>
      #canvas{
        background-color: #1C1C1C;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script>
      var frame = 0;
      //canvas 받기
      const canvas = document.getElementById('canvas');
      //canvas의 2d context 받기
      const ctx = canvas.getContext('2d');
      
      //fit canvas size to screen
      canvas.width = screen.width;
      canvas.height = screen.height;
      let colors = ['red','yellow','green', 'blue','purple'];
      function random(min,max){
        return Math.random()*(max-min)+min;
      }
      //원 객체 정의
      class circle {
        constructor() {
          this.x = 0;
          this.y = 0;
          this.r = 0;
          this.c = colors[parseInt(random(0,4))];
          this.angle = random(0,2)*Math.PI;
        }
        changeAngle(){
          this.angle = random(0,2)*Math.PI;
        }
        move(){
       	  //삼각함수 / angle to sin, angle to cos
          this.x += Math.sin(this.angle);
          this.y += Math.cos(this.angle);
        }
        drawCircle() {
          ctx.beginPath();
          ctx.arc(this.x,this.y,this.r,0, 2*Math.PI);
          ctx.stroke();
          ctx.fillStyle = this.c;
          ctx.fill();
        }
      }
      //객체 배열 생성
      let circles = [];
      //배열에 원 추가
      for(i=0;i<15;i++){
        circles.push(new circle);
      }
      //배열의 원 정의
      for(i=0;i<15;i++){
        circles[i].x = random(0,screen.width);
        circles[i].y = random(0,screen.height);
        circles[i].r = random(50,100);
        circles[i].drawCircle();
      }
      
      // animation 구현
      function animation(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        for(i=0;i<circles.length;i++){
          circles[i].move();
          circles[i].drawCircle();
        }
        if(frame >= 60){
          for(i=0;i<circles.length;i++){
            circles[i].changeAngle();
          }
          frame = 0;
        }
        frame++;
        //매 프레임마다 함수 호출
        requestAnimationFrame(animation);
      }
      animation();
    </script>
  </body>
</html>

오늘 배운 것

this.x += Math.sin(this.angle);
this.y += Math.cos(this.angle);       

원의 좌표계에서 sin@ = x -> 프로그래밍에서도 반영가능
Math.sin , Math.cos 등

requestAnimationFrame(animation);

프레임 마다 특정 함수를 호출하는 함수

          ctx.beginPath();
          ctx.arc(this.x,this.y,this.r,0, 2*Math.PI);
          ctx.stroke();
          ctx.fillStyle = this.c;
          ctx.fill();

원 그리기

profile
Programming begginer

0개의 댓글