Snow Effect in Javascript

snow effect jsThis Javascript creates a snowfall effect on a web page. Thanks to VerkkoNet for his tutorial video. OK, I won’t deny it, I copy pasted a little, but that is only because I don’t know what functions to call. I somehow needed an idea. But now that I know the functions, I’m finally beginning to understand why the code works.

Also, I know this might be a little late since it’s already the spring solstice. It could have been a good animation back in the winter equinox. Perhaps, I should start creating blooming flowers animation instead… anyway…

If you guys want to download the file, you can download it here.

You can also see this as a pen in CodePen.

Let’s talk about the Code

This is our complete code in the HTML file. I will just comment as we scroll down the code. Also, I will only highlight some functions. You guys may have to figure out what others do.

<html>
<head>
	<title>Snow Effect</title>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<style type="text/css">
		body{
			background: #000;
			text-align: center;
			vertical-align: middle;
		}
		#winter-field{
			top: 50%;
			transform: translateX(-50%) translateY(-50%); /* vertically aligns the canvas in the middle of the page */
			position:absolute;
		}
	</style>
	<script type="text/javascript">		
		function init (){
			var portrait = document.getElementById('winter-field');
			var context = portrait.getContext('2d');

                        // .width returns the width of the element
			var w = portrait.width;

                        // .height returns the height of the element
			var h = portrait.height;

                        // create new image function
			var background = new Image();

                        // source of the background image for the canvas
			background.src = "images/snowy_park.jpg";

                        // container for the array of snowflakes
			var snowflakes = [];

			function snowfall (){
                                // clearRect 0 0 and setting width and height to itself not only clears the canvas, it clears all canvas state.
                                // This is ideal for redrawing
				context.clearRect(0, 0, w, h);

                                // set the background image in x-position: 0 and y-position: 0
				context.drawImage(background, 0, 0);

                                // Run addSnowFlake and snow functions
				addSnowFlake();
				snow();
			};

			function addSnowFlake (){
                                // create random numbers and round it off to avoid floating numbers then multiply it to the width of the element.
				var x = Math.ceil(Math.random() * w);

                                // same as above but multiply it with a constant
				var s = Math.ceil(Math.random() * 3);

                                // The push() method adds new items to the end of an array, and returns the new length. Colon passes the value of var x to array of x, y to array of y, and s to array of s.
				snowflakes.push({"x": x, "y": 0, "s": s});
			};

			function snow (){
                                // for loop condition. If i is less than the value of length, increment i
				for (var i = 0; i < snowflakes.length; i++){

                                        // create multiple containers for the snowflakes 
					var snowflake = snowflakes[i];

                                        // The beginPath() method begins a path, or resets the current path. Think of it like your pencil or brush.
					context.beginPath();

                                        // The color of your brush
					context.fillStyle = "rgba(255, 255, 255, 0.7)";

                                        // creates circles in random sizes since var x and s are using Math.random. y is zero but it gets new value from s divided by 2. The circle starts at 0 degree radian, and ends at 2 * 3.14159, making up a 360 degree radius, thus, draws a perfect circle
					context.arc(snowflake.x, snowflakes[i].y += snowflake.s/2, snowflake.s/2, 0, 2 * Math.PI);

                                        // The fill() method fills (modifies) all the elements of an array from a start index (default zero) to an end index (default array length) with a static value. It returns the modified array. This makes our snowflakes go down to the bottom.
					context.fill();

                                        // if the content of the array of y is greater than the height of an element, remove value from array. This makes sure that are snowflakes don't go beyond our height.
					if(snowflakes[i].y > h){
						snowflakes.splice(i, 1);
					}
				};
			};
                        // the time interval between script firing
			setInterval(snowfall, 20);
		};
		window.onload = init;
	</script>
</head>
<body>
	<canvas id="winter-field" width="450" height="298"></canvas>
</body>
</html>

Our code here is lightweight, by adding and removing array context values, we don’t run into memory overload and we lessen CPU usage even when using a full screen canvas.

Another point… setting the multiplier constant for var s from 3 to something higher will make some snowflakes turn into a snowball and will make it fall faster than the others. That is due to the fact that s is use to draw the circles and when multiplied to a bigger number yields a bigger circumference for our circle. s also controls how fast our array is being pushed.

Follow me at:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.