A rarely updated blog about programming and lack of sleep

Make it snow with jQuery

    It is winter time, and you might want to make it snow on your website. Let's try to make it in jQuery!

    Creating the snow

    Create two pictures with snow in some picture editor. It has to be saved in a picture format supporting transparency. 24 bit PNG is a good choice. Make the snow, and make the background transparent. Size doesn't matter, but the picture must be tile-able.

    I made my snowy pictures in Photoshop, and if you already know how to paint snow, jump to next chapter.

    I created a new document, sized 800x800 pixels, with transparent background. I added the layer effect "Stroke", which adds a 3px black stroke around everything I paint on my first layer. Then I choose the brush tool, and changed the brush to vary in size and scatter when I painted it. I choose the color white, and start painting on my picture. This results in random white dots with black stroke, making cartoon snowflakes.

    Then I cropped it down to 400x400 by placing the crop tool in the middle of the image. This was done to avoid the tile effect along the edges. And last, I cleaned up the picture by removing all snowflakes which was either cut by the edges or double, and any snowflakes that was too close to each other.

    Then I did the same thing again, to make two different pictures, but I guess you could also use the same picture and flip it.

    Save both pictures as snow1.png and snow2.png.

    Create the webpage

    Create a default webpage in your favorite text editor and save it as snow.html.

    
    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Snow!</title>
    </head>
    <body>
    </body>
    </html>
    

    In the head tag, add these lines. The first line loads jQuery from Googles API Libraries. The second line loads a jQuery plugin we will download in the next chapter. And the third line loads our own code, which we will write in the next chapter.

    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script type="text/javascript">
    src="jquery.backgroundposition.js"</script>
    <script
    type="text/javascript">
    src="makeitsnow.js"</script>
    

    We will put our snow inside two <div> tags, 500x500 pixels resolution (change this to whatever size you need), with light blue background color. It is important to set background position and tell it to repeat it.

    
    <div id="snow1"
    style="width: 500px; height: 500px; background: lightblue url('snow.png') 0px 0px repeat;">
    <div id="snow2" style=" width: 100%; height: 100%; background: url('snow2.png') 0px 0px repeat;">
    </div>
    </div>
    

    Create the script

    First, you need to download a plugin for jQuery called backgroundPosition. Add this file in the same folder as the rest of your files. Then create a new text file called makeitsnow.js. Open it in your favorite text editor.

    The idea here is to make the two overlapping backgrounds in the html document scroll slowly down, at different speeds, with a slight random angle. This makes for very calm and realistic snow.

    Let us first create a function called "Snow".

    
    function Snow(tag, fallrate)
    {
    this.x = 0;
    this.y = 0;
    this.fallrate = fallrate;
    this.tag = tag;
    

    Snow has two arguments; tag and fall rate.
    Tag is a string deciding which tag in the html code to modify.
    Fall rate is how fast the snow falls.
    X and y is the current position of the background.
    And the keyword "this" refers to the function we are currently inside.

    Inside this function we are going to create two new functions: move() and start().

    
    this.move = function() {
    	this.x = this.x + Math.floor(Math.random()*60)-30;
    	this.y = this.y + this.fallrate;
    	var backPositionString = this.x + 'px ' + this.y + 'px';
    	$(this.tag).animate({
    	backgroundPosition: backPositionString},3000,'linear');
    };
    
    this.start = function() {
    	this.move();
    	var self = this;
    	this.interval = setInterval( function(){self.move()}, 3000 );
    };
    }
    

    We create two variables; this.move and this.start, and place a function in each of them.

    The move function moves the background. It moves a random number between 0 and 60 to the left, and we subtract 30 to make it a random number between -30 and 30. On the next line it moves down equal to the fall rate.
    The third line creates a string containing the x and y, formatted as you would write it when modifying a cascading style sheet (css). This is necessary because the plugin we used only recognizes it this way.
    And the last line uses jQuery to animate the background from its current position to the new position. From point A to B it uses 3 seconds (3000 milliseconds), and it moves with 'linear' movement instead of the default 'smooth' movement. If you remove 'linear' you will see why I did this.

    The start function is there to run the move function once, then every 3 seconds. It had to be done in a kind of roundabout way because for some reason it is not possible to write "setInterval(this.move(), 3000)".

    The final piece of code is this:

    
    $(document).ready(function() {
    	var snow1 = new Snow('#snow1',30).start();
    	var snow2 = new Snow('#snow2',40).start();
    });
    

    It says "when the document is ready" then it creates two Snow objects and starts them. And they have a slight difference in speed to make it look a bit more realistic.

    And with a bit of tweaking, this is what the finished results may look like:

    Download sourcecode

    Comments

    You can download another wordpress plugin version of this snow fall effect here: http://www.mpiresolutions.com/site/development/let-it-snow-wordpress-plugin Let me know what your thoughts are. Loved your example!

    Add new comment