Celebrate the Fourth of July with JavaScript Fireworks

Celebrate the Fourth of July with JavaScript Fireworks!

Many Americans celebrate the Fourth of July by hanging out with friends, having a backyard barbeque while enjoying some cool drinks and watching a wonderful display of colorful fireworks. In honor of the holiday, we thought we’d create our own little JavaScript fireworks display.

Even if you aren’t from America yourself, fireworks can still be fun and beautiful, so come celebrate with us and learn how to create your own cool fireworks display with a bit of JavaScript!

Tools You’ll Need

To begin this project all you need is a modern web browser and whatever text editor you prefer. I’m using Google Chrome and Visual Studio Code, but most anything you are comfortable with will work just fine; even Notepad!

Project Structure

We’ll be using JavaScript for this tutorial because its simplicity and its prominence — just about every computer or device out there can handle JavaScript, so there shouldn’t be any compatibility issues for those of you following along.

Our entire application will consist of just three files:

  • index.html: This is the HTML page we’ll load in our browser to view our finished work.
  • default.css: The cascading stylesheet that contains the (minor) styling adjustments we’ll need to make things look great.
  • app.js: The meat and potatoes of our application. This is where all our firework-generating goodness will reside.

That’s all we’ll need, so start by adding a new directory on your computer and creating those three blank files. Alternatively, you can use an online development playground tool like Codepen, in which case everything will appear in the browser as you follow along.

The End Goal

Since this is an animated fireworks display that we’re going for, it’s rather difficult to portray what the final result will look like in writing. If you want to see what the final product will look like (as well as view the full code all in one place), have a look at this CodePen entry.

Creating the HTML Page

Let’s begin by writing the simple HTML that we’ll need to display our fireworks application. We’re going to be using the powerful canvas API that was introduced with HTML5, which makes it very easy to create all sorts of web-based graphics using real-time languages like JavaScript.

Therefore, most of our drawing and creation logic takes place in the app.js file, so the contents of index.html is fairly sparse. Copy and paste the following into index.html:

Our index.html file begins with a standard DOCTYPE specification, along with the <meta> tag where we specify the character set we’re using, along with the page <title>. We also need to include our default.css stylesheet, so the <link> tag comes next to accomplish that.

Next is our (limited) <script> block. Normally we’d directly include the app.js script file via <script src="app.js"></script>. However, it’s important that we attempt to load the app.js code after our page has fully loaded. Since we’re not using any outside libraries like jQuery, which would normally give us the means to do this automatically, we need a few lines inside the <script> tag to force our HTML page to load app.js after the page has finished loading all other elements.

The final thing we need to add is the <canvas> element, which is where all the magic happens and where our fireworks graphics will actually be drawn.

Creating the Stylesheet

Our style content for this tutorial is extremely simple. Start by opening the default.css file that was created earlier and paste the following into it:

As indicated by the comments, all we’re doing here is changing the <body> background to black and removing the margins. For the critical <canvas> element we’re simply changing the display style to block, which ensures that the canvas stretches the entire width of the page.

That’s all we need to do for styling, since most of the graphics will be created in real-time through our JavaScript code. It’s also important to note here that we’re using so little CSS that we could’ve just included the inline styling directly inside our index.html page using <style></style> tags. However, it’s generally recommended to avoid inline styling, since it helps to keep projects much cleaner by separating styling (CSS) from layout (HTML).

Writing Our JavaScript Code

Finally we get to the fun part — writing some JavaScript code! There are many ways to accomplish the goal of creating fireworks (just browse through the plethora of examples on CodePen and elsewhere), but for this script we’ve opted for a fairly simple approach. Our fireworks display will be made up of two types of elements: fireworks and particles.

A firework (within our code) represents a single trail that is launched from the bottom of the screen to a destination position. Once it reaches its destination, it should explode and create a series of particles, which will shimmer and rain down just like real fireworks!

Configuration

To get started simply open up (or create) the app.js file. One goal of this example is to allow for a lot of customization, so you can easily modify the behavior of nearly all elements of the fireworks to see what cool things you can come up with. Therefore, we begin our app.js file with all the configuration options:

We’ve purposefully opted to use the const keyword for all the configuration settings. This is generally good practice since it ensures we cannot accidentally change the value during runtime. Most of the configuration options are reasonably commented and use appropriate default values, but once our application is up and running, feel free to play with these settings and see what you can do!

The configuration is split into four main categories: Fireworks settings to adjust the behavior of the fireworks themselves, particles to adjust the behavior of explosion particles, canvas coloration to modify global behavior, and tick restrictions to adjust how frequently fireworks are launched.

Local Variables

The next section houses all the local variables. These are not constants, and will be used and modified frequently throughout the entire project. Go ahead and add this next section to app.js:

Again, most variables are commented, but critical ones include the fireworks = [] and particles = [] arrays that we’ll use to keep track all the individual instances that are active at any given time.

Helper Functions

While not required, it’s often beneficial to create a few helper functions in most applications. These should be independent functions that are not tied into the logic or functionality of your application in anyway. Think of them like a library that can be used in virtually any project.

For our purposes we just have a few helper functions to add to app.js:

In addition to random(), used to get a random value within a range, and calculateDistance(), to figure out how far apart two points are, a particularly important helper function is window.requestAnimFrame(). This immediately invoked function expression (IIFE) allows us to call the appropriate requestAnimationFrame() method of whatever browser is being used. requestAnimationFrame() is a smooth way to request that the browser redraw the window, without resorting to weaker techniques like using setTimeout() (which should be a last resort for modern development).

Event Listeners

One small (but fun) feature we’ll be adding is the ability to click anywhere on the page to manually launch a new firework toward that specific position. To accomplish this we need to know where the mouse position is at any given moment, while also tracking when the mouse button is pressed and released. These event listener functions allow us to update relevant variables when the mouse is moved or clicked:

Prototyping

The prototyping section of the app.js code is where the majority of our application logic takes place. This is where we’ll define how fireworks and particles are created, updated, and eventually destroyed. We’ll use the great number of configuration settings we defined at the top of the app.js file, along with elapsed time (in the form of ticks or loops of our animation), to determine what should be changed. This will be a fairly extensive section, so we’ll break it up into functinal sections to make it easier to digest.

As the name of this section indicates, we’ll be using the tried-and-true prototyping technique to create our critical Firework and Particle objects. This allows us to track individual instances of these elements easily, while also assigning each instance a unique set of properties that will affect its behavior.

Handling Fireworks

We begin with the Firework object:

Most of this function is used to set the assortment of properties that the Firework will use elsewhere. Of particular note is the start and end point parameter coordinates, which tell the Firework the path it should travel on. We use these points to calculate the distance it will travel, the angle of trajectory, and so forth.

Next is the Firework.prototype.update() method:

This is where most of the behavioral logic of our Firework takes place. We start by adjusting the trail property array, which we’re using to track a list of active positions that should be used to draw our firework trail graphic.

We also adjust the speed and use the calculated velocity to determine how far this firework has travelled. We use this travelled distance to determine if the firework has reached its target destination, in which case we destroy it and create a new explosion of particles via createParticles().

The final Firework prototype is the draw() method:

This is where all visual updates are made to this particular Firework instance. All we’re really doing is creating a new line that spans between the current position of the firework and the tail end of the firework’s trail.

We also have a second stroke using the arc() method that creates our target circle indicator, showing the position that the firework is heading toward.

Handling Particles

The next section contains the latter half of our prototyping code, which we’re using to handle the Particle elements. As we’ve already seen, Particles are the series of trails that are generated when a Firework reaches its target position and explodes.

Since much of the Particle prototype code is similar to that of Firework, we don’t need to explain it in detail outside of the provided comments, so feel free to add the following to app.js to continue:

Application Helper Functions

Next we need to add a series of helper functions that are specifically tied to the logic and functionality of our application. That means they make direct use of the various app-specific variables and objects we’ve defined, so these functions are distinctly different from the helper functions we defined earlier.

We start with cleanCanvas(), which you can read more about in the source comments, but is primarily intended to cleanup existing trails based on their current transparency/alpha level:

We’ve called createParticles() elsewhere already, and we’re using this method to create a series of new Particle instances when a Firework explodes:

launchAutomatedFirework() is executed every animation loop and determines if enough time has passed to launch another automatic firework. We launch fireworks from the bottom center of the screen and aim them toward a random position in the upper half:

launchManualFirework() is also executed every animation frame and checks if enough time has elapsed to launch a manual firework, assuming the mouse button is currently pressed:

The last two app helper functions are updateFireworks() and updateParticles(), which perform their respective tasks of drawing and updating the status of all existing Firework/Particle elements that are currently active:

Last but certainly not least comes the main loop() function, which drives the entire application by recursively passing itself to each requestAnimFrame() call. This ensure that within each frame, all our Fireworks and Particles are moved, updated, and redrawn as necessary, while also creating any new fireworks that need to be launched. The final snippet of code to add to app.js is as follows:

That’s all there is to it! You’re now ready to open up the index.html file in your browser of choice and watch the fireworks fly. Feel free to click around (or hold the mouse button) to launch them even faster. Best of all, start messing with some of the configuration options to really kick things up a notch. If your system can handle it, I recommend dramatically increasing PARTICLE_COUNT and lowering CANVAS_CLEANUP_ALPHA to really make things come alive! Happy Fourth of July!