Sparkly Particles
Let’s say you are creating a web-based RPG where you are presented with a screen where you have to wave your magic wand over elements on the screen to reveal them (HOG-like). Or perhaps you have a magic-themed game and you want to have a fun “sparkle” effect as you move the mouse around over your interface. Well, the magic of CSS3 animations come to the rescue again!
Note: I know you may find this gratuitous to the nth degree. However, in the case of games, appearances mean a lot. Sure, you may not want this for your next business application, but you may find some aspect of this that helps you add some special polish to your application, or maybe get you thinking differently about CSS3′s application in your project.
So, let’s talk about what’s going on. First off, I set up a bunch of CSS for the background such as a linear gradient, as well as set up overflow : hidden so that any stray sparkles dont fall outside the box. If you want a great tool to generate linear gradients, check out this tool from WestCiv.
Next I wanted to create a bunch of different looking “sparkle” characters, so I created a js function that would randomly return interesting HTML entities that look like sparkles. Next, I wrapped these sparkles with div classes — one for each effect. If you look in the CSS there is a “raise” transform, a rotate transform, a color cycle transform, and a gradual fade from opacity 1 to 0; Each effect has to be on its own element, as you cannot stack transforms on the same element, the same way you cannot have both a red background and a green one – from two different classes.
I set up a listener on the div which triggers on mousemove. Base on a certain probability, I spawn one of the “particles” and the CSS transforms/animations kick in automatically. This is a great example of where doing all this via javascript would have been pretty tedious and probably slow. But since these animations are “native” to the browser, they run very smoothly and fast.
Lastly, I set up a timer via YUI.later for each element to kill itself after a certain time. If I did not do this, I’m sure the browser would eventually slow to a crawl animating all those invisible elements.
This is no substitute for a “real” particle system, but I surprised myself with how nice it looked when I finished the tutorial code. Please let me know if you like/dislike this, and if you have any ideas for additions or changes. Also, if you find that you’ve discovered something new playing with CSS3 Animations or Transitions, please drop me a line!