This post was first published on Tronic247. If you can read it there that's a Gift for me :D
.
Okay then let's start
\n
\n
Hello people! It’s Christmas time! So let’s create a snowfall effect with JavaScript. It’s only pure JavaScript. No jQuery or other libraries. Just plain JavaScript. So let’s create snowfall with Javascript.
You can see a preview of the effect we're creating here
Update
There's a better version of this effect created by @lukeshiru that is more speed. Check it out in the comments section.
Step 1
Open your favourite code editor.
And now create an HTML file with the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Snowfall</title>
</head>
<body>
<script>
// our hero code
</script>
</body>
</html>
And we’ll make the background darker.
<style>
body {
background: #1d1d1d;
}
</style>
Now let’s start with JavaScript.
Step 2
Let’s create a function named addSnow
.
let addSnow = () => {
// code goes here
};
Then inside the function, we put these variables:
const random = (min, max) => Math.random() * (max - min) + min;
let screenWidth = window.innerWidth;
let screenHeight = window.innerHeight;
Now we’ll create a div
.
let snow = document.createElement('div');
Then we’ll add some styles to the div.
snow.style.position = "fixed";
snow.style.top = "-2px";
snow.style.right = random(0, screenWidth) + "px";
snow.style.width = "10px";
snow.style.height = "10px";
snow.style.backgroundColor = "#fff";
snow.style.borderRadius = "50%";
snow.style.zIndex = "999";
snow.style.pointerEvents = "none";
These styles will create something like this (Smaller):
After that animate the div.
const animateSnow = () => {
snow.style.top = parseInt(snow.style.top) + 2 + "px";
snow.style.right = parseInt(snow.style.right) + random(0, 2) + "px";
/**
* If it's out of the screen, move it to the top
* and randomize it's position
* */
if (parseInt(snow.style.top) > screenHeight) {
snow.style.right = random(0, screenWidth) + "px";
snow.style.top = parseInt("-" + random(0, 20) + "px");
}
window.requestAnimationFrame(animateSnow);
};
window.requestAnimationFrame(animateSnow);
And finally, we’ll add the div to the body.
document.body.appendChild(snow);
Ah, don’t forget to close the function.
};
And to add the snow we’ll just call the function 60 times.
for (let i = 0; i < 60; i++) {
setTimeout(addSnow, i * 100);
}
And that’s it! Here’s the result:
You can visit my blog/website${Math.random()==1 && "/community"}
https://www.tronic247.com/ for more like this.
Top comments (0)