티스토리 뷰

Youtube 따라하기

파티클 이펙트

트라이에이스 2021. 1. 29. 17:52

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Floating Particles Effect</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style type="text/css">
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
#canvas1 { position: absolute; width: 100%; height: 100%; background: linear-gradient(#25364f, #4d71a5, #9bc4ff);}
</style>
</head>

<body>
<canvas id="canvas1"></canvas>

<script>
const canvas = document.getElementById("canvas1");
const ctx = canvas.getContext("2d");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
let particleArray;

function Particle(x, y, directionX, directionY, size, color) {
  this.x = x;
  this.y = y;
  this.directionX = directionX;
  this.directionY = directionY;
  this.size = size;
  this.color = color;
}

//이 함수를 이용하여 많은 객체를 만들 것으로 생각되므로 prototype에 함수를 정의하여 
//메모리를 절약할 수 있을 것입니다.
Particle.prototype.draw = function() {
  ctx.beginPath();
  ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2, false);
  ctx.fillStyle = this.color;
  ctx.fill();
}
// add update method to particle prototype
Particle.prototype.update = function() {
  if(this.x + this.size > canvas.width || this.x - this.size < 0) {
    this.directionX = -this.directionX;
  }
  if(this.y + this.size > canvas.height || this.y - this.size < 0) {
    this.directionY = -this.directionY;
  }
  this.x += this.directionX;
  this.y += this.directionY;
  this.draw();
}
// create particle array
function init() {
  particleArray = [];
  for(let i=0; i<100; i++) {
    let size = Math.random() * 20;
    let x = Math.random() * (innerWidth - size * 2);
    let y = Math.random() * (innerHeight - size * 2);
    let directionX = (Math.random() * .4) - .2;
    let directionY = (Math.random() * .4) - .2;
    let color = 'white';

    particleArray.push(new Particle(x, y, directionX, directionY, size, color));
  }
}
// animation loop
function animate() {
  requestAnimationFrame(animate);
  ctx.clearRect(0,0, innerWidth, innerHeight);

  for(let i=0; i<particleArray.length; i++) {
    particleArray[i].update();
  }
}

init();
animate();

window.addEventListener("resize", function() {
  canvas.width = innerWidth;
  canvas.height = innerHeight;
  init();
})
</script>
</body>
</html>

출처: www.youtube.com/watch?v=hotMX-pqjkQ&ab_channel=Frankslaboratory

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함