Wrapping Your Head Around Canvas: Part 6

It’s been sometime since I’ve updated this HTML5 Canvas series, but this article should round out the tutorial series as article 6. We’ve covered creating 2D shapes, images, how to animate said shapes and images, and WebGL basics. In my example from Part 5 we coded together a basic cube with materials. With these foundations set in place we can start diving deeper into WebGL through animating the objects and even piecing together particle effects. If you have any questions please take a moment to revisit my previous articles concerning Canvas:

One of the basics in learning how to work with basic motion in an animation setting, you learn about the physics and force that cause a basic bouncing ball. In the case of creating our particle effect, you can create falling particle that might mimic snowfall or simulate a dynamic ball pit. When we begin coding out our Canvas the pattern we’ll create will seem rather chaotic at first, but we can wrangle it all in to make something amazing. Hopefully by the end of this we can create a group of soft glowing edge particle with random paths that resemble fireflies.

We’ve filled the space with a dark gray, something to make our particle pop against the background. And we’ve positioned the canvas on the page at a left and right of 0. You’ll notice that the variables for our width and height have already been used, this will allow us to dynamically change the dimensions. Getting down to the meat and potatoes of the article we’ll begin adding our first particle against the background.

The arc method helps us create a circle element with the x and y coordinates at 100 and it has a radius of 15. For a more in depth explanation of the arguments for the arc method, read Part 1 of this series. The last method tells our canvas to fill in the particle we just created. Now that we’ve created the particle, let’s bring it to life with a little animation. Let’s wrap our particle in a ‘draw’ function.

By using setInterval we’re telling Javascript which element we want to animate in our first argument, and the speed of acceloration in the 2nd argument. If we increase the interval number, you can begin to see the particle slow down. Adversely if we decrease that interval number, the speed of our particle increases. For the time being ‘110’ seems to be an ideal speed. We’ve also introduced 2 new variables for the x and y properties of said particle.

From this point we’ll need to create an array above our draw function to help create multiple particle on the canvas like so:

var particles = [];
for (var i = 0; i<50; i++) {
//we'd like to keep track of the particles, so we'll
add it to the bottom of our array
particles.push(new create_particle());
}

If you noticed, we’ve created a new function in the last code code snippet, now it’s time for us to define the function:

We can begin to play around with the velocity of each particle to make it appear as if each particle has it’s own random pattern it follows. Just below the code we just wrote about placing the particles around the canvas, place these two lines of code:

Setting the particle size to a random diameter gives us two things, one, not every particle in our scene should be uniform. Uniform is boring. And two, it provides us with a small sense of depth of field. One thing that you’ll notice is that some of our particles have a trail behind them. If we’re setting up a night time scene and mimicking fireflies you would notice a small trail of light but not noticeable enough for you to point it out. We’re going to go back to our ‘draw’ function and play around with the properties a little:

Let’s take a second or so to back up and review our new draw function. the very first line we’re introducing a globalCompositeOperation with the value of ‘source-over’. The reason being is that we’ve already colored the background a black color, that color shouldn’t blend with the previous color or else out background will disappear. From the on the second line we set the red, green, blue, and alpha properties of each particle, then finishing out that section with a fillRect method with properties for our x and y positions, then calling the width and height variables. now that we have those in place we can begin to blend the particle with the background with another globalCompositeOperation with a property of ‘lighter’. This is going to help us setup our gradient glow around each particle.

Now we can begin to draw each particle in the array we setup earlier with our t and p variables. To actually get each particle to appear on stage we round it out with ctx.beginPath();. Here we can start creating the glow around our ‘fireflies’. You can see that we’ve setup a variable of gradient that calls the createRadialGradient method. The gradient.addColorStop method helps us color the particles. For the purpose of this article we’ll be staying with certain shades of yellow, to give us that lighting bug glow. If you place close attention to the progression of the gradient, you can tell that the colors work their way from the inside out, with black being the last color. Then just like our background we create a fillStyle and then an arc.

Congratulations folks! you have successfully created random particles to populate. We can keep moving forward by adding things like velocity by adding the velocities after our gradient fillStyle before we close out the for {} in our draw function:

p.x += p.vx;
p.y += p.vy;

The code that follows the velocity portion of our Javascript constrains the particles to the stage. Like so:

If you have any questions about the results, check out my JSFiddle I built the scene in.

Alternatives

There are options out there to aid you with your particle needs. If someone has gone before you and done the leg work, why reinvent the wheel? Sparks.js is a simple and lightweight javascript library that creates 3D particles for you. It does require you to load three.js in order to work properly, but once combined they can work as a pretty powerful combo. If you want to try your hand at it, check out the in browser editor by Jerome Etienne.

Example

Josh is currently the Creative Director at Rappsody Studios located in Jacksonville, FL and has been working in across the web for close to eight years. He has a soft spot for front-end development and comics.
More articles by Joshua Rapp

Hey WordPress lovers. Every month dozens of incredible free WordPress plugins are released by the community, and we’re here to bring them to you. This seems to be a month of small but useful utilities that only do one or two things, with a few exceptions. So go on. March on down to the list, and get to it! (I'm only a little bit ashamed of that pun.) WP NoteUp ... Notes! Alongside your posts and pages! Use them to remind yourself, or other authors, about things you'd put in a note. That's really all there is to...

WordPress plugins are coming out all of the time, right and left. Every day, they’ve got new ones in the WordPress plugin repository for the curious developer to check out. Over time, your average designer or developer will end up with a list of their favorites. Usually, they’re plugins that solve common problems, are up-to-date and well-maintained, with good support. With that in mind, we’re sharing a list of some of the best plugins out there. Disable Comments ... Disable Comments does......

When I first started out creating websites with WordPress, I was in awe of the depth and variety of plugins available. During those golden days I would willingly install just about anything that looked cool. Shortly thereafter, I was smacked in the head by reality. Stuff started breaking and seriously hurt my good time. It turns out that not every plugin is a great one. And there are times when it seems like the work we do is held together with bubble gum and duct tape. Everything works splendidly until it...

WordPress is undoubtedly one of the most popular tools on the Internet because it makes it so easy to get a functional web site up and running in such a short time. And then there are the plugins. If you want your WordPress site to do something then odds are there is a plugin that you can install to make your site do what you want it to do. But plugins pose a bit of a problem at times. Since they are created by third-party developers you never know what quality control practices are used and what security testing...

WordPress beginners have difficulty customizing their websites past simple text changes, especially if they have no background knowledge of HTML or CSS. WordPress page builder plugins allow just about anyone to build a stylish or professional looking web page, through a user-friendly interface - quickly, and without knowing HTML or CSS. Though it may seem like WordPress page builder plugins have usefulness mainly for the technically unsavvy, they can also make a WordPress developer’s job...

Oftentimes, setting up a WordPress website results in a haphazard scramble to configure enough of the right plugins to make the client happy, and address any specific needs they might have mentioned. But a failure to install certain plugins means the client will come back at you with questions as to why it wasn’t done in the first place. Though you’re probably happy to rectify the problem (and collect a little extra money on the project), going back in to install plugins can distract from more profitable...

In Part 1 of this series we took a look at how you can better secure your WordPress files during, and after, the installation of the software. But once you have the files hardened against different threats, it is time to start looking at some of the different plug-ins available that can help you further protect and secure your WordPress site. WordPress Firewall 2 ... Having worked with a company that deals with web application firewalls, I can tell you from firsthand experience that these are by far one...

There’s a goal behind every website, and a specific chain of events that must occur before each goal is accomplished. Whether you want someone to sign up for your email newsletter, or fill out a contact form, these things don’t happen without the proper triggers. Used strategically, WordPress plugins can assist with the realization of important goals. Here’s how to turn your website into a conversion machine with WordPress Plugins. Essential Grid ... Essential Grid is an all-around grid solution...

About

DeveloperDrive.com is a blog about web development from the makers of the popular web design blog WebdesignerDepot.com
Founded in 2011, we focus on the latest trends, tutorials, opinion articles as well as tips and tricks to empower our readers to become better web developers.