Customer Service in any Organization

Reading Time: 6 minutes


For any profit-based organization, it is often said, “Excellent customer service is the number one job in any company. It is the personality of the company and the reason customers come back. Without customers, there is no company.” This belief has helped many companies achieve success in their respective fields and in this blog I have discussed what really is Customer Service and share my experience of more than 30 years in the field.

So, product service is basically the provision of support (service) to the customer before, during, and after the purchase of the product. Whatever be the situation, the employees of the organization have to adjust themselves to the varying personalities of the customer to ensure success in the field of customer service and the overall success of the company. An organization that values customer service has to spend more resources on training employees/customers than an average organization.

Customer Service in any Organization

An important mantra that any organization should follow while training their employee is that they should believe in proactive customer service rather than reactive customer service. Proactive Customer Service refers to effective planning earlier to tackle all the situations customers put you in. Whereas, reactive customer service refers to acting spontaneously to the complaints of the customer. This often causes a panic situation in the company causing many extreme steps that could further affect the reputation of the organization. 


Role of Customer Service in any Business

Contrary to common misconception, Customer Service also plays a vital role in the overall sales process of the organization and generating revenue of the organization as in today’s industry a lot depends on the reputation of the company. Due to this perspective, customer service should be included as a part of the overall approach of the systematic improvement of the company. It is important to understand that even one good customer service provided can change the entire perception of the customer towards the company.

Customer Support doesn’t limit to just solving a client’s problems with the product. Once the customer buys the product from the organization, it is the organizations’ prime duty to help the customer that he/she uses the product right and cost-effective. To ensure this, the organization has to assist the customer in planning, installation, training, troubleshooting, maintenance, upgrading, and disposal of the product.


Customer Complaint Registration Process

Customer Service may be provided by a person (eg. service or sales representative) or by automated means such as digital kiosks, web sites, and mobile applications.

In the case of a person, a service representative is assigned for taking the complaint directly from the customer. He is basically the point of contact with the consumer for the company. He takes complaints from the customer and assigns the same to the concerned service engineer. The service representative ensures continuous feedback to the customer on the status of his/her complaint until the resolution of the complaint and subsequent feedback to the company from the customer. This has been the go-to mode of customer service for many years but the disadvantage of the method is the time constraint and difficulty in communication between many layers. But these problems are now getting minimized with the help of Automated Customer Service.

One of the advantages of Automated means is an increased ability to provide 24 * 7 hours service, which highly compliments with customers’ needs. Also, customer service is becoming data-driven. So these automated methods could be really helpful. Some of the most popular types of Automated Customer Service are :

i) Artificial Intelligence

ii) Touch-Tone Phone

iii) Online Commerce (Websites)


i) Artificial Intelligence

AI customer service technologies can highly reduce the workload of customer service representatives as it solves minor and some major frequent issues easily. Customers can visually interact with the company’s model and solve their complaints at their own level with the help of proper technology.

Two of the most significant ways AI is augmenting customer service is through AI-augmented messaging and AI email tagging. AI-augmented messaging enables customer service agents to handle a big part of customer queries with the help of chatbot assistants.

Customer Service in any Organization

ii) Touch-Tone Phone

Touch- Tone Phone refers to the customer service dealt with an augmented machine voice that interacts with the customers. It usually involves IVR (Interactive Voice Response), the main menu, and uses the keypad as options to react according to customer’s needs. You might have come across them when you dial mobile connection customer service. (Press 1 for English, 2 for Hindi!)

Customer Service in any Organization

iii) Online Commerce

In the present era organizations are enhancing and maintaining personal experience using the advantages of online commerce. Online customers are invisible and not connected directly which makes it very difficult to effectively communicate with them. Also due to this invisibility, it makes it even more crucial for the organization to create a sense of personal human to human connection. Artificial means of service enables the companies to provide automated online assistants to customers through websites. These methods highly reduce the operating and training costs for the organizations.


Measurement of Customer Service Result

It is very important to keep in check the service provided by the company to the customers and hence Measurement of Customer Service Result is very crucial. Customer Service could be measured in the following ways:- 

i) First Response Time

ii) Restoration Time

i) First Response Time

This indicates how fast an organization responds to the complaints registered by the customer. To ensure minimum response time, an organization must have sufficient manpower for engineers and technicians. Without manpower, it is very difficult to maintain a good first response time which further affects the company.

ii) Restoration Time

Once the response is provided, restoration time is the time by which the customer complaint is completely resolved. To ensure minimum restoration time, the company must have Trained and Manpower and Sufficient stock of Spare Parts.

If the engineer gives a prompt response to the customer’s complaint but he is not well trained by the organization on the product, he/she would be unable to understand the customer complaint and act on it. Hence the restoration time sways away from the target time. Again if a response is given and the engineer is well trained, but if no spare parts are required to solve the complaint’s problem, the restoration time is affected. So have a proactive customer service, the organization should always be well prepared. I have seen all types of situations and it is very important to be in constant touch with time.


Customer Satisfaction (CSAT)

 This term is frequently used by the marketing team of the company. It is a measure of how products supplied and services rendered to the customer has achieved or crossed the customer expectations. Customer satisfaction is defined as the number of customers or percentage of total customers, whose reported experience with the company, its products, or its service index exceeds specified satisfaction goals.

In marketing, the managers found customer satisfaction measuring system very useful in managing and monitoring their business. It is observed as a key performance indicator within business and is also a part of the scorecard analysis of the company. 

In today’s competitive world, customer satisfaction is seen as a key differentiator and increasingly has become a key element of business strategy. In a nutshell, Customer Service or Product Service has been a key industry for the past many years and with the advancements in current technology, customer service will find a new path but the score would remain the same.

Customer Service in any Organization

HTML Canvas Games from Scratch #4

Reading Time: 6 minutes

HTML Canvas Games from Scratch #4

Hello devs!🎮
Let us continue with the game👾
Now we need to implement these functionalities to complete the game:

  • Collide bullets with aliens
  • Healthbar for the player
  • Respawning of aliens
  • Background
  • Score calculation and game over

Let’s do it! 🚀

Phase 4

So we will begin with the code we left last time.
If you don’t already have it, you can download it from : HERE
So we will follow the order of functionalities given above.

Bullet alien collision💥:

So the alien should die if the bullet touches the alien’s body. To do this we will implement a distance() function which will take the coordinates of the alien and the bullet in consideration and check if any collisions occur. We will be iterating through the array Aliens and the array Bullets to check for each pair of {alien , bullet} to check for a collision. Let’s code!

//Checking for bullet kill  
if(Math.abs(Bullets[i].x - Aliens[j].x) <= 18 && Bullets[i].y <= Aliens[j].y && Bullets[i].y>=Aliens[j].y-20 && (player.y - Aliens[j].y) >= 38 )
Bullets[i].y = -10;
var addAlien = new alien(Math.random()*(window.innerWidth-100)+60, Math.random()*(window.innerHeight/2-300),Math.floor(Math.random()*2));
Aliens[j] = addAlien;

Now let us analyse this code.

We are traversing through both the arrays and checking for 4 conditions :

  • Absolute distance between bullet and alien in x axis is less than or equal to 18 (as the aliens are almost 36px in width).
  • The y coordinate of the bullet is less than the y coordinate of the alien.
  • The y coordinate of the bullet is greater than ( alien.y - 20 ).(as the aliens are almost 40px in height)
  • The y coordinate of the space shuttle (center) is at least 38px below the aliens center.(this ensures that the alien and space shuttle are not )

If these conditions are satisfied, we :

  • Update number of kills (variable kills++)
  • Send the bullet out of the screen (y = -10)
  • Add a new alien in place of the dead alien.

Source Code : Code Link
Location in repository : \Phase 4\BulletCollisions

Try and run this code yourself to see the output.


For this we define a new variable called healthBarHeight.
So out health bar height will depend on the health variable, which is initially valued 90. As the aliens touch the shuttle, or the aliens *pass beyond the screen *, the shuttle’s health is reduced.
Turning it into code :

//Drawing the health bar  
if(health == 90){
c.fillStyle = "green";
healthbarHeight = 90*6;
else if(health == 60){
c.fillStyle = "orange";
healthbarHeight = 60*6;
else if(health == 30){
c.fillStyle = "red";
healthbarHeight = 30*6;
healthbarHeight = 0;
c.fillRect(20, 20, 20 , healthbarHeight );

Note : All this is written inside the draw() function.

Well we also need to handle the cases where the player loses health. Write this inside the draw() function :

for( j=0 ; j<Aliens.length ; j++)
if(Math.abs(Aliens[j].y - testShuttle.y) <= 60 && Math.abs(Aliens[j].x - testShuttle.x)<=18 || Aliens[j].y >= window.innerHeight -30){
var addAlien = new alien(Math.random()*(window.innerWidth-100)+60, Math.random()*(window.innerHeight/2-300),Math.floor(Math.random()*2));
Aliens[j] = addAlien;

Try to check what conditions are handled.

Note : As soon as any of the conditions are satisfied, we have also killed the alien. Try removing the last 2 lines inside the if statement and then run the code and see the outcome.

The healthbar would looks something like this :

Source Code : Code Link
Location in repository : \Phase 4\Health

Note : We still need to add the “Game Over” condition. We will do that at the end.

Before moving forward, let us code to increase the difficulty with score.
I.e. as kills increase, so will the speed of the aliens and the number of aliens:

var level = 0; //Declare this at the top  
//Increase difficulty with kills  
//Add this inside "Checking for bullet kill" after Aliens[j] = addAlien;  
if(kills % 10 == 0){
alienSpeed += 0.1;
if(kills % 20 == 0){
var levelupAlien = new alien(Math.random()*(window.innerWidth-100)+60, Math.random()*(window.innerHeight/2-300),Math.floor(Math.random()*2));

At every 15 kills we add a new alien, and at every 10 kills we increase the speed.
Source Code : Code Link
Location in repository : \Phase 4\LevelUp


The game is set in outer space, so whats missing?
Right! Stars✨!
Lets code this separately first:

var maxStars = 150; //Stars on the screen  
var starSpeed = 5;
//Star object  
var star = function(x,y ,rad){
this.x = x;
this.y = y;
this.rad = rad;
Stars = new Array(); //Array of stars  
//Filling the array  
for(a = 0; a<maxStars ; a++){
var temp = new star(Math.random()*(window.innerWidth-20), Math.random()*(window.innerHeight-20),Math.random()*3 );

Now we will be drawing these stars, but every time a star leaves the screen we will place it back on the top. Hence it will be like a single screen just repeating itself.
This is how most of the infinite runner games like temple run and subway surfers take up just a few MB of space.
So here goes the draw function :

function draw(){
//Clear window  
c.clearRect(0,0,window.innerWidth, window.innerHeight);
//Draw stars  
for(j = 0;j<maxStars ; j++){
c.fillStyle = 'rgba(255,255,255,0.7)';
c.arc(Stars[j].x,Stars[j].y,Stars[j].rad , 0 , Math.PI * 2 , false);
Stars[j].y += starSpeed;
//This part send the star back to the top  
if(Stars[j].y >= window.innerHeight-20){
Stars[j].y = 0;


Source Code : Code Link
Location in repository : \Phase 4\Background

Now we need to add this to the game . The background will be drawn regardless of what’s going on in the game so let us straightaway merge the code in the game code, resulting in :

Source Code : Code Link
Location in repository : \Phase 4\BackgroundMerged

Its time to wrap it up by calculating the score and handling the game over condition.

Game 0ver🎌:

To calculate the score there may be different ways. It totally depends on you how do you want to calculate the score.
I personally feel it is best to check the Accuracy and Level Reached:

var alive = 1; //1 alive 0 dead  
function draw(){
//Enter code to draw Stars  
//Rest of the game  
//Check if alien touches shuttle or crosses screen to reduce health  
if(health == 0) //Check if health is 0  
alive = 0;
//Score screen  
c.fillStyle = 'rgba(255,255,255,0.5)';
c.font = "30px Calibri";
c.fillText("GAME OVER!" , (window.innerWidth-20)/2 - 55 , (window.innerHeight-20)/2 - 30);
c.fillText("Kills : " + kills , (window.innerWidth-20)/2 - 15 , (window.innerHeight-20)/2 );
c.fillText("Accuracy : " + (kills*100/totalBullets).toFixed(2), (window.innerWidth-20)/2 - 55 , (window.innerHeight-20)/2 + 30);

This is how the game over screen will look:

So we are now ready with the final game:
Source Code : FINAL GAME
Location in repository : \Phase 4\Final

I’ve added a flickering effect to the alien as it looks cool. 😉
Enjoy playing and share it with your friends too! You can now experiment with the code to add your own effects, functionalities, audio, video and much more.

Play This Game
Play Another Version

Well this is the end of the series. Hope you try and create more such games and visuals on canvas.

If you liked canvas check THIS out!
Do leave suggestion/comments if any.

Written by : Jay Rathod💻
Links : Portfolio | Github | Codepen | Linkedin | Instagram

HTML Canvas Games from Scratch #3

Reading Time: 5 minutes

Hey, devs!🎮
So we are all set to begin creating the game👾.
Let’s do it!

Phase 3

Before we jump into coding, let us plan things.
Objects we will need :

  • Player (The space shuttle)🚀
  • Alien👾
  • Bullets

Let us define these objects :

//Shuttle object
var shuttle = function(x,y){
this.x = x;
this.y = y;
//Alien object
var alien = function(x,y){
this.x = x;
this.y = y;
//Bullet object
var bullet = function(x,y){
this.x = x;
this.y = y;
//Since we will handle multiple bullets and Aliens
var Bullets = new Array();
var Aliens = new Array();

Other variables that we will need to define are :

var totalBullets = 0; //bullets on screen
var health = 90; //health of player
var kills = 0; //total aliens killed
var maxAliens = 5; //Max aliens on the screen
var bulletSpeed = 7; //Speed of the bullet
var alienSpeed = 0.2; //Speed of the aliens

Note : These values are selected by hit and trial.
Now we will need alien and shuttle sprites. I have already made these using fillRect() functions.
Download code from this link : Code Link
Location in repository : \Phase 3\Sprites
Note : It is ok if you don’t try to understand drawShuttle() and drawAlien() as it isn’t very important, those are just figures made using rectangles. You will be using images for sprites in the future mostly.
Result :

HTML Canvas Games from Scratch #3
Space Shuttle will be positioned at the bottom center.
Alien will have a constrained random position at approximately the top part of the screen.

Now we will work on the same code that you’ve downloaded.
Let us add an event listener to enable the space shuttle to move using the arrow keys. (As we did in the previous post)

var keys = []; //Add this before the draw() definition
window.addEventListener("keydown", keysPressed, false );
function keysPressed(e) {
// store an entry for every key pressed
keys[e.keyCode] = true;
window.addEventListener("keyup", keysReleased, false);
function keysReleased(e) {
    // mark keys that were released
keys[e.keyCode] = false;

So we need to adjust the position of the space shuttle before re-drawing it on the canvas. Inside the draw() function, before drawing the space shuttle :

//Handling arrow key presses and shuttle movement boundaries
// left
if (keys[37]) {
if(player.x >= 70)
player.x -= shuttleSpeedh;
// right
if (keys[39]) {
if(player.x <= window.innerWidth - 50)
player.x += shuttleSpeedh;
// down
if (keys[38]) {
if(player.y >= window.innerHeight/2)
player.y -= shuttleSpeedv;
// up
if (keys[40]) {
if(player.y <= window.innerHeight - baseBottomh - midBottomh - cannonh)
player.y += shuttleSpeedv;

Run this code to check what are the constraints to the movement of the space shuttle.
Note : shuttleSpeedh and shuttleSpeedv respresent horizontal and vertical velocity. These have been defined in the file at the top.
Result :
HTML Canvas Games from Scratch #3
Here’s the source code : Code link
Location in repository : \Phase 3\MovingShuttle

Now let us fill the array of aliens:

//Initial array of aliens
for(a = 0; a < maxAliens; a++){
var temp = new alien(Math.random()*(window.innerWidth-100)+60, Math.random()*(window.innerHeight/2-300));
Aliens.push(temp); //We already defined this array

To draw all these aliens we need to make changes in out draw() function. Just add a loop where we are drawing a single alien:

for(a = 0 ; a < Aliens.length ; a++)

Result :
HTML Canvas Games from Scratch #3
Here’s the source code : Code Link
Location in repository : \Phase 3\SpawnAliens

Moving on, we now need to make the space shuttle launch bullets.
This will happen on pressing spacebar. But only 1 bullet will be launched on pressing spacebar once. So the event we use will be keyRelease. Remember we have already defined it?
Let us add more functionality to it.
js  function keysReleased(e) { if(e.keyCode==32){ //keycode of spacebar var temp = new bullet(player.x , player.y - midBottomh - cannonh); totalBullets++; Bullets.push(temp); } }  
Now let us draw all the bullets on the canvas;

function drawBullet(thisBullet){
c.fillStyle = bulletColors[Math.floor(Math.random()*6)];
c.arc(thisBullet.x,thisBullet.y - cannonh + 10, 2.5 , 0 , Math.PI*2 ,false);
c.fillRect(thisBullet.x-2.5,thisBullet.y - cannonh + 10  ,5,5);

Last but not the least lets draw these bullets on the canvas and make them move . This should be added inside draw():

//Check bullets that left the screen and remove them from array
for(a = 0 ; a < Bullets.length ; a++){
if(Bullets[a].y <=0 ){
Bullets.splice(a,1); //Removes 1 element from the array from index 'a'
//Update bullet coordinates to make it move and draw bullets
for(a = 0 ; a < Bullets.length ; a++){
Bullets[a].y -= bulletSpeed; //Already defined at the top

Result :
HTML Canvas Games from Scratch #3
Here’s the source code : Code link
Location in repository : \Phase 3\Bullets

Moving on to the last thing that we will be doing in this phase. Make the aliens move.

Aliens[a].y += alienSpeed; //Add this inside the loop
//where we use drawAlien();

So we have set the aliens in motion!👾

Final source code for this phase : Code Link
Location in repository :  \Phase 3\Final

We are almost done with the game. This phase was about the aesthetics of the game. Next phase will be the final phase where we will add the game logic and a final touch with a good background and a visible healthbar.
Do leave comments/suggestions if any.

 Play the game :

Star this game!

Written by : Jay Rathod💻
Links : Portfolio | Github | Codepen | Linkedin | Instagram

HTML Canvas Games from Scratch #2

Reading Time: 7 minutesHey folks!🎮
So in the previous post I tried to lay a foundation to start understanding canvas. I hope that by now you are a bit comfortable with it. So in the previous post we saw:

  • File structure and boilerplate📁
  • Some important javascript functions for drawing✏️
  • Defining a particle and drawing it on the canvas (hope you remember atom😉)
  • requestAnimationFrame()🔄
  • One and two dimensional uniform motion of the particle🏃
  • Gaining control over the Math.random() function🎲

Phase 2

Till now we were have worked with one particle, but that’s not how games are right? At least most of them. Handling multiple particles is not as tough as you might think. Let’s see how its done!
First of all, will the object definition of the particle change?
Well, it depends on the properties of these particles.
(We will see this later on)

Let us continue with the same particle definition that we previously used:

var particle = function(x,y,radius){
   this.x = x;
   this.y = y;
   this.radius = radius;

Now instead of defining one particle, let us define an array of particles:

var particleArray = new Array();

Let us now define 50 particles with random positions on the screen. But what are the dimensions of the screen?
We already have :

  • window.innerWidth
  • window.innerHeight

So the coordinates of the screen will be in the range:

  • X : 0 – window.innerWidth
  • Y : 0 – window.innerHeight

So the code goes like this :

var totalParticles = 50;         //number of particles 
var maxRadius = 30;               //maximum value of radius   
var particle = function(x,y,radius){
    this.x = x;
    this.y = y;
    this.radius = radius;
var particleArray = new Array(); //array of particles        
var i;                          //loop variable 
for(i = 0 ; i < totalParticles ; i++) {
    //Defining properties of the particle
    var xcoord = Math.random()*window.innerWidth;
    var ycoord = Math.random()*window.innerHeight;
    var rad = Math.random()*maxRadius;
    //New particle with above properties
    var tempParticle = new particle(xcoord,ycoord,rad);
    //Push tempParticle into the array

I’ve tried to keep the code readable and obvious. Just read it and you should understand what is happening.
What’s left? Let us draw these particles on the canvas!
Just add the following code :

c.fillStyle = 'aqua';
//Drawing the particles
for(i = 0 ; i < totalParticles ; i++ ){
    c.arc(particleArray[i].x,particleArray[i].y,particleArray[i].radius,0, Math.PI*2,false);


HTML Canvas Games from Scratch #2

Here’s the source code : Code link
Location in repository : \Phase 2\ParticleArray

Note : On refreshing the page you will find a new configuration everytime.
Also we haven’t used the requestAnimationFrame() function as we just wanted static particles as of now.

What next? Let us give all the particles some random velocities🚀.
We need to add two properties for the particle object “x velocity” and “y velocity“:

var particle = function(x,y,vx,vy,radius){
this.x = x;
this.y = y;
this.vx = vx;              //x vel
this.vy = vy;              //y vel
this.radius = radius;

Now since we have added new properties for this object, we must also define its values for all the defined instances.

Wait, did I just go too hard on you?😝

Ok let me reframe that:
Since we added two new properties to the particle object, we also need to give the value of these properties for all the particles that are stored in the array.
So inside the for loop in which we are defining and adding particles to the array :

    var xvel = Math.random()*6 - 3;
    var yvel = Math.random()*6 - 3;
    var tempParticle = new particle(xcoord,ycoord,xvel,yvel,rad);

Try figuring out the range of (xvel, yvel).

Now we are ready with particles and their velocities. Lets start drawing them on the canvas. This time we will use requestAnimationFrame():

c.fillStyle = 'aqua';        //define fillStyle
function draw(){
    //Clears the entire canvas
    //Update the value of the coordinates (according to velocity)
    for(i = 0 ; i < totalParticles ; i++ ){
        particleArray[i].x += particleArray[i].vx;
        particleArray[i].y += particleArray[i].vy;
    //Drawing the particles
    for(i = 0 ; i < totalParticles ; i++ ){
        c.arc(particleArray[i].x,particleArray[i].y,particleArray[i].radius,0, Math.PI*2,false);

Result :

HTML Canvas Games from Scratch #2

Here’s the source code : Code link

Location in repository : \Phase 2\ParticleArrayMoving

It must be noted that the particles will soon disappear leaving a black screen. The reason being that the canvas extends infinitely, we just get to see a part which our window can capture.
To confine the particles to our window, we must make the window act as a box 🔳. Particles must collide and bounce back inside like this:

HTML Canvas Games from Scratch #2

These conditions are to be taken care of every time before drawing the particles. Let us code them:

//Checking for collison with walls
for(i = 0 ; i < totalParticles ; i++ ){
        if(particleArray[i].x > window.innerWidth || particleArray[i].x < 0)
        if(particleArray[i].y > window.innerHeight || particleArray[i].y < 0)

Result :

HTML Canvas Games from Scratch #2

Here’s the source code : Code link
Location in repository : \Phase 2\ParticleArrayMovingCollisions

Notice the particles bouncing off the edges.

Practice Sesh💻 : You can try giving a different color to all the particles. You can also try to making all the particles twinkle/shimmer✨, by changing its opacity (the ‘a‘ in rgba).

Solutions to these : Link to code

Location in repository : \Phase 2\Practice Sesh

Interacting with the canvas:

Yes, chill❄️. It is possible. Obviously. Who would call it a game otherwise?
Let us talk about the addEventListener() method. As the name suggests, it simple listens to events. Events in this case are keyboard inputs, mouse clicks , changes in mouse movements etc.



Event : An event is nothing but a trigger. It is used to execute a coded response. Eg : click , onmousedown , onkeypress , onkeyup etc. (Know more..)
Function: This is the function that is to be called when that specific event occurs. It is defined somewhere in the code.
useCapture : This is either true or false. It is optional. It is used to define whether the event should be executed in the Bubbling or Capturing phase (it is not important right now, though you can read more here). By default it is false.

Lets start with the most basic event and response :
For this you will need the javascript code where we had just 1 static particle.(try to write this code yourself once)
Source code : Code link
Location in repository : \Phase 1\Atom Particle
Just remove the line of code used to increment the speed. Thus getting us a static particle.
Now let us add a simple mouse click event : (append this snippet at the end of the code.js file)

window.addEventListener("click", move , false); //define event listener
function move(e)            //response function                                              
    atom.x = e.x;            //update x coordinate of atom        
    atom.y = e.y;            //update y coordinate of atom

What is ‘e’ ?
e here represents the event, and the event here is click. It must be passed as a parameter to the function.
Every event has specific properties. For this click event, we have properties x and y which represent the coordinates of the cursor on clicking.

Coming back to the code, the function replaces coordinates of atom with the coordinates of the cursor. Thus moving it to the click position.
Check it out yourself.
Source code : Code link
Location in repository : \Phase 2\ParticleCanvasInteraction

Similarly, let us make atom move left , right, up and down with the arrow keys.
So this is what we need :

  • On pushing down an arrow key the particle should move.
  • On releasing the key the particle should stop its movement.

We will use the keydown and keyup events.
This even has a specific property called keyCode. Every key on the keyboard has a different keyCode. The keyCode values of arrow keys are :

  • Left : 37
  • Up : 38
  • Right : 39
  • Down : 40

Let us define a boolean array called “keys” which will hold true for all those keyCodes which are pressed.
Also we will need two event listeners, one that will check for keys pressed and the other that will check for keys released.

var keys = [];
window.addEventListener("keydown",keyPressed,false); //keydown listener
window.addEventListener("keyup",keyReleased,false);      //keyup listener
function keyPressed(e){             //sets value true when key pressed 
    keys[e.keyCode] = true;
function keyReleased(e){            //sets value false when key released
    keys[e.keyCode] = false;

Its not done yet. We need to make required adjustments in the draw() function, the effect of key presses on the coordinates :

function draw(){
    if(keys[37])                //if left is true
        atom.x-=xspeed;         //move left by xspeed
    else if(keys[39])         //else if right is true
        atom.x+=xspeed;         //move right by xspeed
    if(keys[38])                //if up is true
        atom.y-=yspeed;         //move up by yspeed
    else if(keys[40])         //else if down is true
        atom.y+=yspeed;         //move down by yspeed

Note : These are grouped this way because Up and Down cannot function together, and Left and Right cannot function together.

Also don’t forget to define xspeed and yspeed outside the draw function.

Result :
HTML Canvas Games from Scratch #2
Source code : Code link
Location in repository : \Phase2\ParticleCanvasInteractionKeyboard

Now its your turn to play around with a few more such events.

Other things you can try :

  • Bound the motion of this particle to the box
  • Comment out the clearRect() function and see the output
  • Use the fillRect() function with black colour but opacity less than 1, instead of clearRect(). (Will give a nice trail effect)

This is all for this post. Till here I have covered everything it takes to create the game that I made. Now all we have to do is combine all this logic in one file ❗
In my opinion you may also start creating the game yourself, or try making some other game maybe ping-pong, flappy bird, snakes etc.

Do leave comments/suggestions (if any).

Written by : Jay Rathod💻
Links : Portfolio | Github | Codepen | Linkedin | Instagram

HTML Canvas Games from Scratch #1

Reading Time: 7 minutes

Hey there! This is my first blog about HTML Canvas Game Dev video_game.
There are a lot of other tools and libraries available for game dev which are easier to use, but canvas remains my favorite as it takes us to the root of how to code game physics. It is also a great way for beginners to get a good grip on Javascript (speaking from experience).
Thanks to my friend Ronik Gandhi <@rawnix> for introducing me with canvas.

At the end of this series you will be able to build a basic 2D game on your own.

In this series I will walk you through the steps to build a classic Space Invaderspace_invader game which I named SPACE-X.

It will look like this.

Do star star my repo ( if you liked the game.

Let's get started rocket

[Note: We will be creating games for pc only. They won't be responsive.]

Basic Files and Boilerplate

┣ 📂assets
┃ ┣ 📂Images
┃ ┗ 📂audio
┣ 📜index.html
┗ 📜code.js

Get these folders and files ready. As of now we won't be using any assets, we will instead use javascript functions to create shapes.

This game without any images can be played [here]

The index.html file will look something like :

<!DOCTYPE html>
<canvas id="canvas" style="background-color: black"></canvas>
<script type="text/javascript" src="code.js"></script>

This index.html file consists of a canvas tag which is present inside the body tag.
There will be no more changes to this. Rest of the coding will be done in the code.js file.
The code.js file is linked after the closing body tag.

The code.js file will look something like:

var canvas = document.querySelector('#canvas');
var c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;  
  • The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.
  • The getContext() method returns an object that provides methods and properties to draw on the canvas. In this case since '2d' is mentioned, we can draw text, lines, rectangles, circles etc.
  • Next we set the height and width of the canvas equal to the device window's height and width device (this can be changed according to your preference).

Now we are all set to begin coding the game!

Clone/Download this repository before beginning for all the source code.

Phase 1

In this phase we will be working with particles and particle physics.
It is important to keep this in mind that the coordinate system of the canvas is laid down such that the origin is at top left corner of the screen :

Before getting your hands dirty, these are some important methods you should be familiar with to draw on a canvas:

c.clearRect(x1,y1,x2,y2); //clears the canvas inside this rectangular area  
c.beginPath(); //Used to begin drawing a shape  
c.closePath(); //Used to finish drawing a shape  
c.fillStyle = 'red'; //Defines color to be filled in the shapes  
c.fillStyle = '#ffffff'; //rgb,rgba and hex formats are also allowed  
c.fillStyle = 'rgb(12,243,32)';
c.fillStyle = 'rgba(233,12,32,0.4)';//'a' is used to define opacity  
c.fill(); //Fills color  
c.strokeStyle = 'red'; ` //Defines stroke color (rgb,rgba,hex)  
c.stroke(); //Strokes the boundary or the figure  
c.font = "50px Calibri"; //Defines font properties of text  
c.fillText("text" , x, y); //Writes text,top left of text is at (x,y)  
c.arc(centerx,centery,radius, //Creates an arc with given properties  
start angle in radian ,
ending angle in rad ,
counterclockwise true or false);
c.moveTo(x,y); //Moves context cursor to (x,y)  
c.lineTo(x,y); //Draws line from current context cursor coordinate to (x,y)  

NOTE : It is better to use beginPath() and closePath() separately for each connected figure.

A few sample code snippets: Code Link

Location in repository: \Phase 1\Sample Code

Try playing around with the code a little to get a better understanding of the working.
Also it takes time to get used to the syntax of these functions, so hands-on practice is the only solution.

Now let us try to code a particle in canvas.
Consider a particle object in a two dimensional plane. It will have properties:

  • X Coordinate
  • Y Coordinate
  • Radius

It is considered that the particle is a circle.
This is how we can represent the same in javascript :

var particle = function(x,y,radius){
this.x = x;
this.y = y;
this.radius = radius;
//'this' refers to the owner object, i.e. an instance of particle  

The above code defines an object type which is like a datatype , specifically it is a user-defined datatype. That means, now we can create variables of this type.
Lets create one named "atom".

var atom = new particle(100,100,30);  

This line creates a particle which can be referred with the variable "atom". It has the coordinates (100,100) and its radius is 50, but we still cannot see it on the canvas.

Note : All quantities are to be considered in 'pixels'.

Let us bring it to life by drawing it.

c.fillStyle = 'aqua';
c.arc(atom.x,atom.y,atom.radius,0, Math.PI*2,false);

It is now drawn on the canvas. But now what if you want to set it in motion let us say to the right ?
You need a continuous loop in which:

  • Canvas is cleared
  • X coordinate of atom is incremented
  • Atom is re-rendered on the canvas

The continuous loop is generated using the requestAnimationFrame() method.
The requestAnimationFrame() method calls the function, which is passed as a parameter, 60 times in one second. So now, we need a function for repetitive calling. Let us call this function 'draw' :

var xspeed = 1; //Define x direction speed  
function draw(){
//Clears the entire canvas  
//Update x coordinate  
atom.x += speed;
//Drawing the particle  
c.fillStyle = 'aqua';
c.arc(atom.x,atom.y,atom.radius,0, Math.PI*2,false);
requestAnimationFrame(draw); //Called inside the function  
draw(); //Initial function call  

Result : In every consecutive function call, x coordinate of atom is incremented by the value of xspeed variable. To increase the speed, increase the value of xspeed.
Here is the source code : Code link

Location in repository : \Phase 1\Atom Particle

Similarly if you introduce a variable yspeed, which updates the y coordinate of atom, it will lead to a uniform straight line motion in the 2d plane.

var yspeed = 2;
function draw(){
atom.y += yspeed;


Javascript Math.random() function :

This deserves a separate section as it is very important to understand the working of the random function and how to control it. This function will be used very often in games for example:

  • To spawn new enemies at random locations
  • To spawn random powerups at random locations
  • To give random moving directions to objects etc.


var x = Math.random();  

x gets assigned a random float value between 0 and 1 .

Note: value is inclusive of 0 but not 1.

Few outputs of the random function:

  • 0.1882848343757757
  • 0.3605824495503056
  • 0.04217502958085739

How to get a random number between 0 and 1000?

var x = Math.random()*1000;  

This still gives a float value. For integer values:

var x = Math.ceil(Math.random()*1000);
//Output: integer between 0 to 1000 both inclusive  

Math.ceil() function rounds a number up to the next largest whole number or integer.
There is another function called Math.floor() which returns the largest integer less than or equal to a given number.

Note : Lower bound is still 0.

How to get a random number between 500 and 1000?

var x = Math.ceil(Math.random()*500) + 500;  

Here initially Math.ceil(Math.random()*500) function returns values between {0,500} , thus on adding 500 to this range we get the new range {500,1000}.

How to get a negative range lets say -250 to 350?

var x = Math.ceil(Math.random()*500) - 250;  

If you aren't able to figure out how, try finding individual outputs of all the functions in the code one at a time.

This is all for this blog, in the next blog we shall see:

  • How to handle multiple particles
  • Random function in action
  • Collisions
  • Controlling the objects through user input

Written by : Jay Rathodcomputer
Links : Portfolio | GitHub | Codepen | LinkedIn | Instagram

What do you think about “DOOR” ????

Reading Time: 3 minutesThis friday we planned to have among ourselves a discussion on a topic, selected on the spot and that to abstract one. Everytime we usually analysed on some most critical and trending topics in technology and usually turns up to hostels with a concerned mind, but this time each of us experienced in ourselves integration of all small positivity and creativity in memebers before GD.

The topic selected by majority was “DOOR”!

Here is the stream of beautifull thoughts of CEVians on it-

1.) OPPUTUNITIES: Door simply represents a stage just behind any opportunity, you just have to get up and open it, and you have grabed it.

What do you think about "DOOR" ????

2.) EFFORTS: Door has some inertia, either you want to open or close it you have to apply force. Same with life either you want start new or you want to get out from something that you are struglling long, you have to put efforts.

3.) DISCIPLINE: Door is useless without locking system, so that who enters the room completly depends on you, similarly, with discipline in life you have to decide which thoughts or habits you let flow into your mind.

What do you think about "DOOR" ????

4.) EXPLORATION: Either you open the door of your room or close it you are always having a possibility of exploration with you, only the subjects change. When you open it you are having numerous options to explore the world- the people, the places, the nature, etc. and when you close it you create a opportunity to discover youself, for example Issac Newton did a great part of his work when he was alone, suffering with nervous breakdown.

5.)PSYCHOLOGY: Any door in this world creates two systems one inside and one outside, what you see depends in which part you are. Say there are two world, an imaginary one in which every stuff is according to you and there is a real world.

6.) TRANSPARENT: If doors were like opportunities and if they  were transparent then we would without getting into it we could have get an overview of it and could take better decisions.

7.) COURAGEOUS: A stopper of door when dropped can resist very high velocity wind from one side but still easily moved in other way round, this inspires us to stand tenancious against bad situations in life though retaining an affectionate and cheerful character simultaneously.

8.) FORTITUDE: A door closer makes the door shut down everytime, whether opened vigorously or gently, in this way we can develop in us a diligence to react to harsh situations, and turn back to same life leading morals.

What do you think about "DOOR" ????

9.) SAFETY: Door is the thing that stands for safety and privacy, hence they have a great significance.

9.) Any door was not a door before it was a door, may be made up of wood, plastic or steel, it has its own story how it reached there, and also has a life a lead ahead.

10.) And finally a point to take care that overdose of creativity has not been delivered-

Doors are a great invention by civil engineers they are of many types-

i.) framed and panelled doors

ii.) glazed doors

iii.) flush doors

iv.) louvered doors

v.) revolving doors

vi.) collapsible steel doors

vii.) rolling shutter doors

hats off to civil engineers……….🤣🤣🤣

Be creative and cheerfull.

Thanks for reading.


CEV - Handout