Fire effect with CSS3

26 Mar 2011

This effect has been created with some Javascript for setting different CSS3 text-shadow’s in a div. You can check the iframe’s code to see how it’s done. Basically, the Javascript function creates 3 text-shadows (white, yellow and red) with coprime “cycle durations” so the effect looks more random even though it’s totally deterministic.

Each shadow moves in the Y axis with a linear function and in the X axis with a cosine function. Pretty simple, but effective.

<script type="text/javascript">
var step = 0;
function nextShadow(){
    shadow1 = Math.cos(step/3)*2+"px -"+(step%5)+"px "+(step%5)+"px white";
    shadow2 = Math.cos(step/3)*5+"px -"+(step%17)+"px "+(step%17)+"px red";
    shadow3 = Math.cos(step/3)*5+"px -"+(step%31)+"px "+(step%31)+"px yellow";
    $('#onfire').css("text-shadow", shadow1+", "+shadow2+", "+shadow3);
    step++;
}
$(function(){
   setInterval(nextShadow, 10);
});
</script>

Update: I’ve added some randomisation to the algorithm, as well as an individual animation to each of the letters (which, as a drawback, makes the effect run less smooth). I’ve also added a fourth shadow in dark yellow. You can freely use the code by keeping the mention to this site and my name on it.