Lens Flare in JavaScript

Far from being limited to Photoshop filters, video games and film CGI effects, a basic implementation of lens flares can work quite well in JavaScript too. This jQuery plugin allows you to add a lens flare effect to images. Move the Sun around below.

The Sun

The effect works by distributing various flare images at proportional distances along a line projected from the Sun through the centre of the viewport and on to the opposing side. In the sunset demo, we deliberately cut-off the lens flare as the Sun moves out of shot.

Flare Images

All of the flare and Sun images are 8-bit (256 colour, palletised) PNGs with alpha. In most situations this is a good alternative to 32-bit PNGs as there is a significant size saving. Fine gradients can look a little banded, but this can be mitigated somewhat with dithering.

IE6 Issues

While the plugin code works perfectly well in IE6, the transparent PNG images do not. There are some work-arounds to enable PNG alpha support in IE6, but frankly, as this is just a cosmetic effect, I would simply not bother turning the effect on for IE6. In most applictions (excluding this page of course), the end user will be none the wiser.

In the space demo above, we have basic occlusion as you move the Sun behind the Earth. This actually works rather well, and the effect would be further improved if varying opacity could be applied correctly to images with alpha channels. This would allow us to fade in and out of the lens flare, rather than just on or off. Unfortunately, opacity only seems to work correctly with non-alpha images. You can also move the small star in the bottom corner, although no occlusion is applied.

This is probably of limited use within a regular web document, but a <canvas> version would be good for games.

It's certainly not compulsory, but if this software has been useful to you, then a link back to this page would be very welcome. Also, if you have used the plugin on your website, then send me a link and I'll be happy to post it here.

blog comments powered by Disqus
Share |

Useful website? You can donate to support it. Thanks.

Integration instructions to follow.

Need Good Hosting?

Hostgator Reliable Hosting

I use Host Gator for this site, and have found them to be good value and very reliable. Sign up now and use coupon code professorcloud to receive a $9.95 rebate.

Books to improve your JavaScript skills