본문 바로가기
Javascript/GMA(2302~)

230502 자바스크립트 캔버스 이용하여 움직이는 파티클 만들기

by hyerin1201 2023. 5. 18.


HTML

<body>
  <canvas></canvas>
</body>

Javascript

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

function Circle(x, y, radius, color) {
  this.x = x;
  this.y = y;
  this.radius = radius;
  this.color = color;

  this.dx = Math.floor(Math.random() * 4) + 1;
  this.dy = Math.floor(Math.random() * 4) + 1;

  this.draw = function() {
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
    ctx.fill();
  }
  
  this.animate = function() {
    this.x += this.dx;
    this.y += this.dy;

    if(this.x + this.radius > canvas.width || this.x - this.radius < 0) {
      this.dx = -this.dx;
    }
    if(this.y + this.radius > canvas.height || this.y - this.radius < 0) {
      this.dy = -this.dy;
    }

    this.draw();
  }
}

const objs = [];
for(let i = 0; i < 30; i++) {
  const radius = Math.floor((Math.random() * 50) + 10);
  const x = Math.random() * (canvas.width - radius * 2) + radius;
  const y = Math.random() * (canvas.height - radius * 2) + radius;
  const color = `rgba(${Math.random()* 255}, ${Math.random()* 255}, ${Math.random()* 255}, ${Math.random() * 1})`;
  objs.push(new Circle(x, y, radius, color));
}

function update() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for(let i = 0; i < objs.length; i++) {
    let obj = objs[i];
    obj.animate();
  }
  requestAnimationFrame(update); //재귀함수
}
update();