티스토리 뷰
<!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
'Youtube 따라하기' 카테고리의 다른 글
파티클 이펙트2 (0) | 2021.02.01 |
---|---|
Clip-path를 이용한 텍스트 애니메이션 (0) | 2021.01.04 |
Anime.js를 사용하여 Vanilla JS로 SVG 모핑 페이지 전환 만들기! (0) | 2020.12.21 |
WebGL을 이용한 호버 효과 (0) | 2020.12.14 |
버튼 호버 효과 (0) | 2020.12.11 |