Big-Bang with JavaScript

Fahad Haidari
4 min readJul 3, 2019

In this article, I’ll show you how to create a simple Big-Bang simulation with JavaScript.

Big-Bang

Check the video below to see the Big-Bang in action!

Are you ready? If so, grab your coffee/tea. I’m waiting…

First of all, let’s create a directory (a fancy name of a folder) for our app, then let’s create 3 files in this directory: index.html, big-bang.js, and style.css

index.html

<!DOCTYPE html><html>  <head>     <link rel=”stylesheet” type=”text/css” href=”style.css”>     <title>Big Bang</title>  </head>  <body>    <canvas id=”canvas”></canvas>    <script src=”big-bang.js”></script>  </body></html>

Note that, we created a <canvas> element to draw our particles on it and included the big-bang.js script

style.css

html, body {  background: #000;  margin: 0;  overflow: hidden;}canvas {  display: block;  background: #000;  margin: 0 auto;}

Now, let’s discuss big-bang.js step by step

window.onload = function() {}

Now the rest of the code will go within this window.onload function… the onload function will be triggered once the web page has completely loaded.

Next:

const canvas = document.getElementById("canvas");const context = canvas.getContext("2d");const particles = []; // an array to keep track of each particleconst colors = ["blue", "green",  "orange", "red", "white", "#4488FF", "yellow"];const timeToStart = (60 * 2); // almost 3 seconds till the simulation will startlet countToStart = 0;canvas.width = window.innerWidth; // full width Canvascanvas.height = window.innerHeight; // full height Canvas

Briefly, we grab the Canvas element to draw graphics on it, then we get the context object, which is responsible for drawing things on the Canvas.

particles is an array that keeps track of each particle.

colors is an array to that holds a collection of random colors, which then we’ll use to fetch random colors from it to draw each particle based on that color.

timeToStart and countToStart will be used to have some delay before the Big Bang started.

Then, we setup the Canvas width and height to fill the entire window.

const random = (min, max) => Math.random() * (max - min) + min;

random is simple helper function that generates a random value between min and max values.

Next:

const createParticles = function(n) {  for (let i = 0; i < n; i ++) {    particles.push({      x: canvas.width / 2, // center the particle on the x axis      y: canvas.height / 2, // center the particle on the y axis      color: colors[parseInt(random(0, colors.length))],      size: random(2, 7),      alpha: random(0.5, 1),      speed: random(10, 100), // speed to scale up the vector      vel: { // velocity unit vector      x: random(-.1, .1),      y: random(-.1, .1),    }  });  }};

Just create n particles (each as an object) and push them to the particles array.

Each particle will be placed in the middle of the Canvas (almost, due to the top-left registration point).

The most important two props in each particle object is the vel vector.

Note: Vector is a mathematical component that holds two important information: magnitude and direction. However in our scenario here, we’re creating a unit Vector (a Vector that has a magnitude of 1) because we only care about it’s heading (where it’s going to), then we’ll multiply its x/y axis by the speed later on to move the particle on a specific direction.

Read more about vectors on MathIsFun

Next:

const update = function() {  countToStart ++;  if (countToStart > timeToStart) {    particles.forEach(p => {      p.x += p.vel.x * p.speed;      p.y += p.vel.y * p.speed;    });  }};

The update function will take care of moving each particle based on its velocity Vector on both x/y axis and multiplied by the speed.

Also, note that we’ll not start the simulation until we hit the desired time, which is 3 seconds (60 * 3).

Next:

const draw = function() {context.clearRect(0, 0, canvas.width, canvas.height);  particles.forEach(p => {    context.fillStyle = p.color;    context.globalAlpha = p.alpha;    context.fillRect(p.x, p.y, p.size, p.size);    context.globalAlpha = 1;  });};

draw function will loop through each particle and draw it based on its color, alpha, x, y, and size (width and height are the same because we’re drawing a Square).

Next:

const tick = function() {  update();  draw();  requestAnimationFrame(tick);};

tick function will make sure to recursively call the update and draw functions on each tick, when it’s ready to draw.

Note that requestAnimationFrame should call tick 60 times/second in best cases.

Read about requestAnimationFrame method on MDN

Next:

createParticles(1000); // pass the number of particlestick();

Lastly, we create our particles, then we call the tick function to start the simulation.

Note that there are many areas of improvements can be done here, for example: calculating the delta time (time between last tick and current tick) and multiply that value by the velocity to ensure a more stable version of movement.

I hope you enjoyed reading this article :)

Let’s Big-Bang!!

Get the code from GitHub

Connect with me on LinkedIn

Follow me on Twitter

Subscribe to my YouTube channel: Game Code Bites

Check my latest games on the App Store:

Go Up Up

Don’t Let the King Fall

--

--