This page shows the graphic effect simulation of fireworks using a particle system, implemented with Typescript using the Canvas element.
Above my implementation of a firework graphic effect is shown. It is implemented in Typescript using HTML5 canvas.
Feel free to download the source code at the top of the page to check out how it works.
The base is a simple 2D particle system. A particle system consists of a set of particle, where a single particle can be thought of an element having a position, speed and acceleration value in the two-dimension plane.
It might be drawn on the screen in a custom way, e.g. as single pixel, as circle, as rectangle or as image.
Further, a particle could have additional properties like a color (including alpha value) or a lifespan (and thus an "active" and "inactive" state) after which it is not updated and visible anymore.
Also a force may be applied to a particle changing the acceleration and thus speed and position.
Particle are used in following ways here:
The main rocket is a single particle with a random color out of five colors. It is rendered as circle with a radial gradient between white and the color of the particle.
It starts at the bottom with varying speed and angle to the top. A vertical force is applied (gravity) that slows down the particle. One its vertical speed reaches zero, it explodes.
While the rocket shoots above, it emits several grey smoke particles. A smoke particle starts at the position of the rocket, moving down and slightly left or right with varying speed. It has a random factor that slowly fades the smoke particle out, this make it more and more transparent until it is not visible at all. Then the smoke particle is removed from the system and and a new smoke particle is spawned at the position of the rocket. The position of the smoke particles are adapted to the movement of the rocket.
Once the rocket explodes, it's particle is removed and a bunch of exploding particles are created. They all start at the former location of the rocket and "explode" into all directions. Also they are forced to bottom by gravity and slow fade out.
Finally a small summary of the used classes and files:
GraphicsLoop: Contains the main class handling the periodic update and drawing of the HTML5 canvas element. Uses the FPS class to calculate (and optionally limit) the frames per second.
Vector2D: Represents a Vector class with two elements (x and y) for a two-dimensional vector containing the most important vector operations.
Particle2D: Implements a two-dimensional particle with position, speed, acceleration and color. The function to finally draw the particle is specified by the user at runtime.
FireworkParticle: A subclass of Particle2D, adding a factor value to fade out the particle.
Firework: Contains the main implementation of a firework with the update and drawing of the rocket, smoke and explosion particles.
App: Main application containg the handling of several fireworks and GUI handling.