A very simple Christmas decoration that can be added on to any web site is a candle - a simple image can quickly be created using applications such as Sib, KIconEdit, or even Microsoft Paint. However, it's also very easy to create a flickering Christmas candle with just four images and some Javascript code.
The Images for a Christmas Candle
A simple Christmas candle would need two images
- the body of the candle (which could consist of a simple rectangle)
- a vertical flame (a simple yellow oval would suffice)
However, a flickering candle will need two additional images:
- the flame blown to the right
- the flame blown to the left
Displaying the Christmas Candle
The Christmas Candle can be displayed by using standard HTML, and in this case:
- all of the images are grouped together in a div - it's this that is used to define where on the screen the candle will be displayed
- to start with only the vertical flame will be visible
And so the HTML will look something like:
Of course this will display a static candle - the next stage is to animate the flame.
Adding a Flicker to the Flame
A flicker can be added to the candle's flame very easily by alternately making each of the images visible and then invisible:
- if flame 1 is visible then make flame 1 invisible and flame 2 visible
- if flame 2 is visible then make flame 2 invisible and flame 3 visible
- if flame 3 is visible then make flame 3 invisible and flame 1 visible
This can easily be translated into a Javascript function:
In this example the function resubmits itself so that it repeats every 500 milliseconds (0.5 seconds). However, there is a drawback to this: the flicker is very regular and has a 1,2,3,1,2,3 pattern. Obviously the next step is to add a random element to the candle's flicker.
Adding Randomness to the Flickering Flame
The flame of a real candle does not simply flow from left to right and back to left again; in the case of this 3 position candle there will be the following possibilities:
- the left image can either remain unchanged or change to the vertical image
- the vertical image can remain unchanged, change to the right image or change back to the left image
- the right image can either remain unchanged or change to the vertical image
In this second function a random decision making process has been added to give a more realistic flicker:
Conclusion
This short tutorial has shown just how easy it is to:
- add a Christmas candle to a web page
- animate the flame of the Christmas candle
- give the flame of the Christmas candle realistic movement
And this simple technique can be applied to other Christmas themes:
- a waving Santa
- Rudolf with moving eyes
In each case it's only the images that would need to change whilst the code can remain the same.