Created
December 23, 2019 17:44
-
-
Save antoniobuconjic/a1ea7fda7034b5fe0fb8118b3c5c61b5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const MaxWind = 2 | |
const FlakesNumber = 100 | |
const radianFromDegree = (degree) => { | |
return degree * (Math.PI / 180); | |
} | |
const getRandomInt = (min, max) => { | |
min = Math.ceil(min); | |
max = Math.floor(max); | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
const getRandomFloat = (min, max) => { | |
return (Math.random() * (max - min + 1)) + min; | |
} | |
// xSteps returns an array with 360 steps in sine with random | |
// sine height limited with param | |
const xSteps = (maxSineHeight) => { | |
if (maxSineHeight < 1) { | |
maxSineHeight = 1 | |
} | |
let sinHeight = getRandomInt(1, maxSineHeight) | |
let arr = [] | |
for (let i = 0; i < 360; i++) { | |
let sin = Math.sin(radianFromDegree(i)) // -1 to 1 | |
let modifiedSin = sin * sinHeight | |
arr.push(modifiedSin) | |
} | |
return arr | |
} | |
let flakes = [] | |
for (let i = 0; i < FlakesNumber; i++) { | |
let elem = document.createElement('div'); | |
let widthHeight = getRandomInt(4, 10) + "px" | |
elem.style.width = widthHeight | |
elem.style.height = widthHeight | |
elem.style.left = getRandomInt(0, window.innerWidth) + "px" | |
elem.classList.add('flake') | |
document.body.appendChild(elem); | |
flakes.push({ | |
velocity: getRandomFloat(0.7, 1.5), | |
elem: elem, | |
xSteps: xSteps(MaxWind), | |
sinIndex: 0, | |
}) | |
} | |
const animationFrameCallback = () => { | |
flakes.forEach(flake => { | |
// update y | |
let cpy = flake.elem.style.top | |
let currHeight = Number(cpy.replace("px", "")) | |
if (currHeight > window.innerHeight) { | |
flake.elem.style.top = "-5px" | |
} else { | |
flake.elem.style.top = (currHeight + flake.velocity) + "px" | |
} | |
// update x | |
if (flake.sinIndex == 360) { | |
flake.xSteps = xSteps(MaxWind) | |
flake.sinIndex = 0 | |
} | |
let copy = flake.elem.style.left | |
let currentLeft = Number(copy.replace("px", "")) | |
let newLeft = (currentLeft + flake.xSteps[flake.sinIndex]) + "px" | |
flake.elem.style.left = newLeft | |
flake.sinIndex++ | |
}) | |
setTimeout(() => { | |
window.requestAnimationFrame(animationFrameCallback) | |
}, 1000 / 60) | |
} | |
window.requestAnimationFrame(animationFrameCallback) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment