Last active
June 7, 2020 10:13
-
-
Save mnngfl/691c247e8faddd8f9c4546e21f94a574 to your computer and use it in GitHub Desktop.
Raindrop animation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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 = []; | |
// INIT | |
function setup() { | |
canvas = document.getElementById("mycanvas"); | |
ctx = canvas.getContext("2d"); | |
for (let i = 0; i < N_RAIN; i++) { | |
rains[i] = new Rain( | |
Math.floor(Math.random() * canvas.width), | |
Math.floor(Math.random() * 80) - 80, | |
Math.floor(Math.random() * 30) + 10, | |
Math.floor(Math.random() * 10) + 2 | |
); | |
} | |
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) { | |
this.x = x; | |
this.y = y; | |
this.l = l; | |
this.vy = vy; | |
} | |
Rain.prototype = { | |
// 캔버스에 빗방울 객체를 그리는 과정 | |
draw: function () { | |
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(); | |
}, | |
// 이전 상태로부터 좌표를 업데이트하는 과정 | |
update: function () { | |
this.y += this.vy; | |
if (this.y + this.l >= canvas.height) { | |
this.x = Math.floor(Math.random() * canvas.width); | |
this.y = Math.floor(Math.random() * 80) - 80; | |
this.l = Math.floor(Math.random() * 30) + 10; | |
this.vy = Math.floor(Math.random() * 10) + 2; | |
} | |
}, | |
}; | |
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