If you have some information or images stored in an array and every time you wish to show those things in random order, then you may need to shuffle the array. Fisher-Yates algorithm is one of the efficient algorithms that can be implemented to achieve this task.

Suppose we have an array a[] containing n elements. The modern Fisher-Yates algorithm follows the given steps-

Iterate through the array from i=n to 1 (assuming the array starts from 0 and we will skip the first element). So, the loop runs n-1 times.

At each iteration,choose a random number j between 0 and i and select the random element a[j].

Swap a[i] and a[j].

To generate the random number we will use the JavaScript’s built-in math function Math.random() which returns any floating number between 0 and 1. Since, we need an integer we will round it up using Math.floor() function.

Knowing how to handle collision between different objects of varying shapes will come in handy if you are into game development or just enjoy solving algorithmic problems. In this post I discussed the conditions to determine the collision between circles, non-rotated rectangles and collision between rectangle and circle.

Circle-Circle collision

Two circles collide if the distance between them is less than the sum of their radii. i.e

The distance is calculated using Pythagoras formula by taking the sum of the square of the differences of x-coordinates and y-coordinates of two circles and square rooting them.

Now, let’s write the code-

var c1={
x:30,
y:25,
r:10;
}
var c2={
x:20,
y:25,
r:10;
}
var dx=c1.x-c2.x,
dy= c1.y-c2.y,
dist=Math.sqrt(dx*dx+dy*dy),
rdist=c1.r+c2.r;
if(dist<=rdist){
console.log("Collision detected!");
}

Rectangle-Rectangle Collision

Rectangles collide if there is no gap between them and here the rectangles considered must be non-rotating.

We find the closest point of the rectangle from the circle’s center. If the distance of this point from the center is less than the radius, then the two shapes collide. The nearest point is found by clamping circle’s center to rectangle’s coordinates.

var circle={
x:40,
y:60,
r:20;
}
var rect={
x:35,
y:50,
w:100,
h:50;
}
var nX=circle.x-Math.max(rect.x,Math.min(circle.x,rect.x+rect.w),
nY=circle.y-Math.max(rect.y,Math.min(circle.y,rect.y+rect.h);
if(nX*nX+nY*nY<=circle.r*circle.r){
console.log("Collision!");
}

Note that the rectangle here must not also be rotated.

Here, I have discussed random motion of particles inside a canvas and bouncing off the boundary. However, I will skip the collision between particles in this post which is a bit tricky and maybe I will do another post only on that topic.

Run the codepen to see the demo with code.

I have created an object called Circle and given it x and y coordinates and speed(sx,sy) in both directions with radius 5. The function drawCircle() uses arc shape function to draw a circle on canvas.

Next, to move the circle we need to change it’s x and y position. We do this by adding speed to current x and y position and then update the position, more the value of speed the faster the circle will move at each frame.

Now, we need to handle some conditions when the x-coordinate of circle is less then 0 or more than canvas width. If the circle’s x position is less than or equals 0, we change the x-coordinate to it’s radius and move it in the opposite direction by multiplying speed with -1. Again if the x-coordinate is more than the canvas width, the speed is changed as before but this time the x-coordinate is updated by subtracting the radius from width of canvas. We do the similar thing for y-coordinate.

The array circles[] stores position and speed of each circle. Both position and speed for any circle is random, which finally gives us the effect of particles moving randomly! The speed is a random value between 0.5 and 5. Finally, requestAnimationFrame runs the update() function and the canvas is cleared and drawn at each frame.

Ever thought of making your own To-do list web app or a game that can save user’s high score? Then Local Storage may help to make your life a little easier. Local Storage stores data in the browser and the data will remain save even if the browser is closed.

Local Storage stores data with key/value pair, that means for each data there is a corresponding key and when the key is entered, data is retrieved.

We need to know some methods to use this API-

Methods

localStorage.setItem(key,value)

localStorage.getItem(key)

localStorage.removeItem(key)

localStorage.clear

localStorage.key

localStorage.length

Let’s illustrate these methods using a simple example. Suppose we ask for user name and it can be save and delete. First we set up the HTML page-

We will be using localStorage API with JavaScript and I will explain the important steps.

var userName=document.getElementById('userName'),
savedName=document.getElementById('savedName');
var add_name=function(){
var name=userName.value;
localStorage.setItem('user',name);
savedName.innerHTML='Hello '+name;
}
var delete_name=function(){
savedName.innerHTML="";
localStorage.removeItem('user');
}
document.getElementById('addName').addEventListener('click',function(){
add_name();
});
document.getElementById('deleteName').addEventListener('click',function(){
delete_name();
})
window.onload=function(){
if(localStorage.length>0){
var key=localStorage.key('user')
savedName.innerHTML='Hello '+localStorage.getItem(key);
}
}

On line 6, the name is saved usinglocalStorage.setItem and the key for the name is given as ‘user’, you can use any other string or variable.

On line 12,localStorage.remove is called with the key and this removes the stored value from the localstorage’s array.

On line 23, when the browser is opened we check if there is any data previously stored using localStorage.length.This checks the number of elements in the array of localStorage. If it is 0 it won’t do anything,but if it is greater than zero, we retrieve the key using localStorage.key which gives the key name. Then finally we get the value of the corresponding key using localStorage.getItem which provides the required data.

Another method we haven’t use in our example is localStorage.clear. What it does actually is it remove all the elements saved in localStorage from the browser, so you should be careful using this one.

Eloquent JavaScript-This book covers almost everything from basic to advance features including chapters on canvas element of HTML5 and Node.js . The book is also available free on their website.

JavaScript Definitive Guide-This is not an easy book to read and I haven’t myself finished it yet, but it teaches you the right coding style and advanced features.