[canvas 강의] 이펙트

M_yeon·2023년 5월 3일
0

canvas

목록 보기
5/5
post-thumbnail

현재 강의에서 비,눈 등 내리는 이펙트를 만들 수 있는 방법을 알려주었다.

const canvas = document.querySelector("canvas");

const ctx = canvas.getContext("2d");
console.log(ctx);
const dpr = window.devicePixelRatio;

const canvaseWidth = innerWidth;
const canvaseHeight = innerHeight;

canvas.style.width = canvaseWidth + "px";
canvas.style.height = canvaseHeight + "px";

canvas.width = canvaseWidth * dpr;
canvas.height = canvaseHeight * dpr;
ctx.scale(dpr, dpr);

// ctx.fillRect(10, 10, 50, 50);

class Particle {
  constructor(x, y, radius, vy) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.vy = vy;
    this.acc = 1.03;
  }
  update() {
    this.vy *= this.acc;
    this.y += this.vy;
  }
  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, (Math.PI / 180) * 360);
    ctx.fillStyle = "yellow";
    ctx.fill();
    ctx.closePath();
  }
}

const TOTAL = 20;
const randomNumBetween = (min, max) => {
  return Math.random() * (max - min + 1) + min;
};
let particles = [];

for (let i = 0; i < TOTAL; i++) {
  const x = randomNumBetween(0, canvaseWidth);
  const y = randomNumBetween(0, canvaseHeight);
  const radius = randomNumBetween(50, 100);
  const vy = randomNumBetween(1, 5);
  const particle = new Particle(x, y, radius, vy);
  particles.push(particle);
}

// 60 FPS
let interval = 1000 / 60;
let now, delta;
let then = Date.now();

function animate() {
  window.requestAnimationFrame(animate);
  now = Date.now();
  delta = now - then;

  if (delta < interval) return;

  ctx.clearRect(0, 0, canvaseWidth, canvaseHeight);

  particles.forEach((particle) => {
    particle.update();
    particle.draw();

    if (particle.y - particle.radius > canvaseHeight) {
      particle.y = -particle.radius;
      particle.x = randomNumBetween(0, canvaseWidth);
      particle.radius = randomNumBetween(50, 100);
      particle.vy = randomNumBetween(1, 5);
    }
  });

  then = now - (delta % interval);
}

animate();

내릴때 중력을 준것처럼 자연스럽게 하려면 * 1.03을 해 주었는데,
0.99를 곱하게 된다면 0이 되면서 서서히 멈추게 되는 이모션도 만들 수 있다.

0개의 댓글