The Firefly Effect



Cosmic pictures are used on many websites as the background image. Those pictures are undoubtedly beautiful, but after all they are still images which provide little liveliness. With jQuery, we can bring a still cosmic image thirty life by adding some space dust (particles) flying like fireflies. In this tutorial, we'll see how to implement this effect in 30 minutes. We'll learn a bit of object-oriented Javascript techniques as well.


  1. Particles move at random speeds and directions (Brownian Motion).
  2. Four models of particles are provided in this tutorial. Each has slightly different looks.
  3. The total number of particles is configurable.

We'll be gazing at this cosmic background for quite a long time. To make our eyes more comfortable, a dark and simple image is used as the background in this tutorial. Feel free to use more colorful images in your own projects.

The Particles

To make this effect look more realistic, we have four models of particles in this tutorial. They're tiny images with different size and looks. Look at the figure below for more details:

  • Particle 1 is smaller but brighter. It looks as if it's right in focus so that we can see it clearly.
  • Particle 4 is bigger but darker (so dark that you can barely see it), which mimics an object out of focus.


Unlike most tutorials, it is the background of a web page on which we'll be focusing today, which makes the HTML quite simple:

  • There are no elements within the body tag. So nothing will distract us from the background and the animation.
  • With the CSS definition, a cosmic background is set for the body of this page. This should be very straightforward.
  • jQuery is included as usual.

Object-Oriented JavaScript

Now let's take a closer look at a particle's life. Each particle may differ in looks. And they move at different speeds and directions. But they all follow the same set of rules which can be described as a sequence of actions:

  1. Randomly pick a particle model.
  2. Create a DOM for this particle.
  3. Generate a random speed for this particle.
  4. Generate the initial position (Point X and Point Y) for this particle.
  5. Display the particle at the position generated in 4.
  6. Generate another position (Point X and Point Y) to which the particle moves.
  7. Animate the particle movement to the position generated in 6.
  8. Repeat 6 and 7 once the animation mentioned in 7 finishes.

Each particle follows exactly these eight steps throughout its lifetime. And the random factors, such as position and speed, make each particle behave in a unique way. This is a perfect case to implement some object-oriented programming techniques. Let's wrap these eight steps in a 'class' which will be instantiated many times to created multiple instances of the same logic. Each instance (particle) runs in a separate lane and holds its own speed and direction.

It's important to note that there are no classes in JavaScript. Functions can be used to somewhat simulate classes, but in general JavaScript is prototype-based rather than class-based. Everything is an object. For more information on how to define and instantiate a JavaScript 'class', please checkout these articles.

In this very effect, a 'class' is defined and then instantiated 50 times with the following code.

  1. The eight-step logic is wrapped in a function named Particle. Defining a function is the way to define a 'class' in Javascript.
  2. We'll need to generate a lot of random integers in this effect, from speed to X-Y positions. So let's write a function for this sole purpose and name it randomInt. It generates a random integer less than a given number. We'll use this function from time to time, so don't forget about it.
  3. At the end, we instantiate the Particle function in a loop, creating 50 instances of particles, each of which stored in an array named particles. Pay attention to the 'new' keyword that we use to instantiate an object.

Some Basic Settings

In this section, we'll define properties and methods for the Particle class. And we'll see how to randomly pick a particle model.

We can use the 'this' keyword to define properties for a 'class'. When it comes to defining methods, the 'prototype' property is the way to go. Look at the code below and we'll give some explanations.

  1. In Line 2 and 3, we define the path and filenames of our particle images. There are more than one particle images so we store them in an array (a property of Particle).
  2. In Line 6, a random particle image is picked from the array mentioned above. The randomInt function we defined earlier is used here. Very handy, hah?
  3. In Line 7, we concatenate the path and the filename.
  4. In Line 10, an img DOM is created. This is the container of a particle.
  5. Line 13 is the core of this effect. A sequence of methods are called in a chain. This single line of code covers Step 3 through 8 mentioned in the previous section. We'll go through each of these methods very soon.
  6. From Line 17 all the way to the end, four methods are defined for the Particle class. Each of them takes care of one particular thing for a particle. Speed() generates the random speed. NewPoint() generates a random set of X-Y position. Display() makes sure that the particle is displayed properly. And fly() takes care of the animation.
  7. Pay attention to the way we define methods for a 'class' in Line 17, 20, 23 and 26. New methods are defined in the prototype property of a class. It may seem a bit tricky to guys from a C, Java or PHP background (like me). If you feel uncomfortable with this, feel free to spend a minute reading this article.

In fact there are many different ways to define properties and methods for a Javascript class. Here's a great article on this topic.

Random Speed

By now, we have an idea how this effect works. From this section, we'll start writing functions that we use to manipulate the movement of a particle.

First, let's generate a random speed for a particle. The speed determines how fast a particle travels. If you are familiar with jQuery, you'll understand we can't just pass in real speed, say 100 pixels per second. In fact, the parameter used to describe speed in jQuery is duration measured in milliseconds. So the question becomes how to generate a reasonable duration in which a particle travels from one place to another. What about the following code?

  1. In Line 3, we simply generate a random integer between 5000 and 14000. That is to say, a particle will keep its speed and direction unchanged for 5 – 14 seconds before taking a turn and moving towards somewhere else.
  2. Look at Line 5. Why do we return this? Remember these functions will be called in a chain? Returning the original object ensures the trailing function to work properly. We'll need this in other methods as well.
  3. Once this function is executed, a duration property in accessible in a Particle instance.

Random Position

A random set of X-Y position is very useful in this effect. It can be used to determine:

  • At which point a particle shows up initially,
  • To which point a particle moves once it is born or finishes a journey.

Here's the code we need to generate a random set of X-Y position.

The size of the current browser window can be retrieved from window.innerWidth and window.innerHeight. If a particle flies beyond the boundary of the window, scrollbars will show up. We may not want that to happen. So let's confine the particle movement in an area which is 100 pixels less high and wide than the browser window. The above code should be pretty straightforward. After this function is executed, pointX and pointY properties become accessible. Once the function runs a second time, pointX and pointY will be renewed in the instance of Particle.

Display the Particle

In previous sections, an img DOM was already created for a new particle. Now we're going to set a few attributes and display the particle somewhere in the browser window. This is accomplished with the following code.

  1. In Line 3, this.element contains the created img DOM. We'll set attributes for it in this function.
  2. In Line 4, this.file contains the random image we picked from the four particle models. By setting the src attribute, we bring the particle image to the new img DOM.
  3. With Line 5 to 7, the particle is positioned somewhere in the browser window.
  4. In Line 8, the img DOM that has just been created is appended to the body. The particle will never show up unless we write this line of simple code.

Animate Particle Movements

Finally, we have come to the animation part which may turn up simpler than you thought.

The animate function in jQuery will do the trick for us. It takes four parameters: animate( params, duration, easing, callback ). Checkout the documentation if you have no idea what it does.

What the above code does is quite simple:

  1. It animates the particle to a random position.
  2. The animation takes this.duration milliseconds to complete.
  3. The particle moves at constant speed. (Easing mode is 'linear'.)
  4. Once the animation is complete, the code in Line 8 will be executed as callbacks.
  5. In Line 8, a new speed will be generated, a new position will be calculated and the fly() function (the very one we're writing in this section) will be executed again.
  6. Repeat from Step 1.

So the fly() function calls itself repeatedly. With this recursive function, the animation goes on and on forever. By now, we are able to write the whole story of a particle's life. Still remember the following chain?

Let's review what it does:

  1. A new speed is generated.
  2. A new set of X-Y position is calculated.
  3. The particle shows up at the position calculated in Step 3.
  4. A new position is calculated.
  5. The particle moves to the position calculated in Step 5.
  6. New speed is generated.
  7. A new set of X-Y position is calculated.
  8. The particle moves to the position calculated in Step 7.
  9. Once the animation is complete, repeat from Step 6.

If these steps sound like a tongue twister to you... Well, look at this figure again. You should be able to code every single step now. And you should know how to organize all the stuff in an object-oriented structure. Finally the firefly effect is complete.


Now everyone should be able to implement this effect in your own projects. Hopefully you have a better understanding of object-oriented Javascript as well.

The number one thing I love about this effect is that by changing the background and particle images, you can produce completely different looks and feel. You can have planes or even supermen flying on your web page if you like. Your imagination is the limit.

That's all for this tutorial. Hope you enjoy it. Thanks for reading!