Skip to content

Instantly share code, notes, and snippets.

@mnngfl
Created June 7, 2020 10:27
Show Gist options
  • Save mnngfl/ef173568bd703cf167ac8f518949b114 to your computer and use it in GitHub Desktop.
Save mnngfl/ef173568bd703cf167ac8f518949b114 to your computer and use it in GitHub Desktop.
Raindrop animation (Add bottom collision effects)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Falling rain Animation</title>
<style>
canvas {
background-color: rgba(27, 27, 47, 1);
background-image: linear-gradient(
to bottom,
rgba(27, 27, 47, 1),
rgba(0, 0, 0, 1)
);
}
</style>
<script>
// GLOBAL
let N_RAIN = 10; // 생성할 Rain 객체 수
let canvas, ctx;
let rains = [];
function random(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(min + Math.random() * (max - min));
}
// INIT
function setup() {
canvas = document.getElementById("mycanvas");
ctx = canvas.getContext("2d");
for (let i = 0; i < N_RAIN; i++) {
rains[i] = new Rain();
rains[i].init();
}
window.requestAnimationFrame(loop);
}
// LOOP
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < rains.length; i++) {
rains[i].update();
rains[i].draw();
}
window.requestAnimationFrame(loop);
}
// RAIN
function Rain(x, y, l, vy, hit, r, vr, a, va) {
this.x = x;
this.y = y;
this.l = l;
this.vy = vy;
this.hit = hit;
this.r = r;
this.vr = vr;
this.a = a;
this.va = va;
}
Rain.prototype = {
// 최초 실행 혹은 빗방울이 바닥에 다다랐을 때 프로퍼티 초기화 시키기
init: function () {
this.x = random(0, canvas.width);
this.y = Math.floor(Math.random() * 80) - 80;
this.l = random(10, 30);
this.vy = random(2, 10);
this.hit = random(canvas.height * 0.8, canvas.height * 0.9);
this.a = 1;
this.va = 0.96;
this.r = 5;
this.vr = 1;
},
// 캔버스에 빗방울 객체를 그리는 과정
draw: function () {
if (this.y + this.l < this.hit) {
ctx.beginPath();
ctx.strokeStyle = "white";
ctx.lineWidth = "0.7";
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.x, this.y + this.l);
ctx.stroke();
} else {
ctx.beginPath();
ctx.strokeStyle = `rgba(255, 255, 255, ${this.a})`;
ctx.ellipse(
this.x,
this.y,
this.r * 0.4,
this.r * 1.2,
Math.PI / 2,
0,
2 * Math.PI
);
ctx.stroke();
}
},
// 이전 상태로부터 좌표를 업데이트하는 과정
update: function () {
if (this.y + this.l < this.hit) {
this.y += this.vy;
} else {
if (this.a > 0.03) {
this.r += this.vr;
if (this.r > 15) {
this.a *= this.va;
this.vr *= 0.98;
}
} else {
this.init();
}
}
},
};
window.onload = function () {
setup();
};
</script>
</head>
<body>
<h2>Rainy day 🌧</h2>
<canvas id="mycanvas" width="640" height="480"></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment