Home

Fireworks!!!

- Anshul Kashyap; August 2, 2018

Hello Everyone:

Ok, let me tell you a story. In sixth grade, I didn’t know the first thing about programming. But then I met two people. They were both passionate programmers and not just that... they also wanted to spread their knowledge and help other people learn as well. It’s because of them that I have such an interest in this field and want to really progress in it as well. I want to be just like them and teach as many people as I can about this field, software development in general, so that they might be able to grasp onto that passion and a new generation of amazing programmers will appear. Obviously, this blog is meant to teach people of all ages. You are never, and I mean never, too young or too old to learn anything. I just hope that I make a big change in this world.


Overview:

Today, we will be looking at the Canvas API and how we can use it to make fun, slick, and interactive websites. We will be working on a small project in this tutorial I like to call Fireworks. We will be using the Canvas API to make a simple animation/interactive website. Sooo… let’s get started :) .


Canvas API Info:

The html5 “canvas” tag is used to draw graphics and can be used for multiple situations. Some of these include game development, other interactive websites, the professional use of graphics, etc. The list goes on. The Canvas API provides us with multiple pre-built functions that makes it easier for the programmer to draw graphics and make their websites more interactable.


Let’s Begin!!:

Let’s start of by creating a simple Canvas using the canvas tag html5 provides us with. Create a new canvas using the "canvas" tag and set the id to "canvas".


Note:

Most of the programming we will be doing in today’s entry will be javascript based. Make sure you have some knowledge of javascript and maybe even OOP programming concepts(It will be a lot easier to understand).


Moving on to the Good Stuff:

Create your js file. To interact with the Canvas object in the html file, we have to create a new var that allows us to use the Canvas object in the js file. Observe the following.

          //Creating the js Canvas object using the .getElementById() function
          var canvas = document.getElementById("canvas");
          //Setting the width and height of the canvas. Should be self explanatory :)
          canvas.width = screen.width;
          canvas.height = screen.height;
          //Contains the necessary methods to draw graphics on the Canvas
          var ctx = canvas.getContext('2d');
                    

Now we have created the Canvas object in the js file. Using this, we will be able to display graphics and manipulate them as well.


Introducing... EventListener!!:

We will be able to create “fireworks” when the user clicks the screen. To do this we have to enable the canvas object to be able to “listen” for information, in this case when the user clicks on the canvas.

          canvas.addEventListener("click", click, false);
                   

Here, you can see that .addEventListener() has three parameters. The first one is the type of event listener, in this case click. This is prebuilt into the Canvas API. It recognizes that “click” means that the click function will be used which as I said before, is prebuilt into the API. The second one is the function that will be executed in the js file after the Canvas is clicked, in this case click(). The last parameter is a boolean value representing whether or not the click function will “bubble” or not. In this case, it is not important so I will not go in depth.

Take a look for more information on bubbling: https://javascript.info/bubbling-and-capturing


Particlesss:

For this web application, we will be making fireworks. The fireworks will be made out of individual Particle objects. Let’s create the particle object constructor. Take note below.

          function Particle(x, y){
              //x and y vals
              this.x = x;
              this.y = y;
              //width and height vals
              this.width = 8
              this.height = 8
              //vx and vy vals
              this.vx = Math.round(Math.random() * 10);
              this.vy = Math.round(Math.random() * 10);
              //Conditionals to equal out the distribution
              if(Math.round(Math.random()) % 2 == 0){this.vx = -this.vx;}
              if(Math.round(Math.random()) % 2 == 0){this.vy = - this.vy;}
          }
                   

The particle object has multiple attributes. An x and y value to keep track of its’ position, a width and height to make it visible, a VELOCITY x and a VELOCITY y (This is very important as it simulates the gravitational effect for the particles), and finally, two conditional statements that allow the distribution of particles on the left and right to be random but decently equal.


Global Variables:

We need some type of array to store the x and y values of the particles. Let’s create two arrays, one to store the x values of the particles and one to store the y values.

In the js file, create four global vars:

          //x and y vals
          var xInitial = [];
          var yInitial = [];
          //Box array stores the particles as individual objects
          var box = [];
          //The amount of particles generated per click
          var max = 20;
                   

Drawing the Particlesss:

Okay, say we created some particles. But... the particles themselves are just pieces of data storing the x, y, vx, vy, width, and height values. We aren’t really rendering or manipulating, rendering, or most importantly drawing the particles. We have to create another function that renders and draws the particles to the Canvas.

          Particle.prototype.draw = function(index){
              //Setting the rgba value to a random color, to help differentiate between particles
              //All the particles are different colors
              ctx.fillStyle = "rgba(" + Math.round(Math.round(Math.random() * 1000)/3.9) + ", " +     Math.round(Math.round(Math.random() * 1000)/3.9) + ", " + Math.round(Math.round(Math.random() * 1000)/3.9) + ", 0.8)";
              //Increasing velocity gives a better visual understanding of the gravitational effects
              this.vy += 1;
              //Changing the x and y vals
              this.x = this.x + this.vx;
              this.y = this.y + this.vy;
              //Drawing the rectangle to the Canvas
              ctx.fillRect(this.x, this.y, this.width, this.height);
          };
                   

Here we can see that we are rendering the x and y values of a pixel object as well as drawing it to the Canvas as well. We are changing the x and y values based on the effects of the velocity parameters.


Click Function:

We want to display a set of particles every time the user clicks on the Canvas right? To do this, we have to create a function that generates a new array of particles to represent a firework. Now, we want create a firework every time the user clicks, as stated above. Go back to the eventListener method. What should the name of the function be?? That’s right, we should name it “click”.

          function click(e){
              //For indexing purposes
              arrLength = xInitial.length;
              for(var i = 0; i < max; i++){
                  //Setting the initial x and y values (the point where the user clicked) for each particle in the current firework
                  xInitial.push(e.clientX);
                  yInitial.push(e.clientY);
              }
              for(var i = 0; i < max; i++){
                  //Adding the particles to the box var
                  box.push(new Particle(xInitial[arrLength + i], yInitial[arrLength + i]));
              }
          }
                   

We can see that we are first adding the x and y values which are determined based on the point where the user clicked. Then we are creating a new Particle and adding it to box with the x and y values as the parameters.


Render Method:

Finally!!! The heart of the project, the render method. Using this method, we will be able to update the frames and draw the particles onto the Canvas. This is the heart of the project and allows us to give the viewer an animation-like effect.

          function render(){
              //Controls the frame rate, like a game loop
              setInterval(function(){
                  //Drawing the background allows us to refresh the frames. Without it, each particle would leave behind a stream of particles tailing it
                  ctx.fillStyle = "rgba(0, 0, 0, 0.2)";
                  ctx.fillRect(0, 0, screen.width-screen.width/100, screen.height-screen.height/11.5);
                  for(var i = 0; i < box.length; i++){
                      //The draw function draws each box to the canvas one by one
                      box[i].draw();
                      if(box[i].y > screen.height-screen.height/6){
                          //If the individual particle has “fallen” out of the canvas, delete it from the vars. This saves memory and allows us to theoretically create as many fireworks as we want.
                          box.splice(i, 1);
                          xInitial.splice(i, 1);
                          yInitial.splice(i, 1);
                      }
                  }
              }, 30);
          }
          //Call the render method at the end
          render();
                   

In the render method, we manage everything from the frame rate to drawing the individual boxes onto the Canvas.


Click Here to See the Finished Version!!


For more resources visit: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial