Many time you want to move a object (div, img) on specific path.
suppose your path is not much complicated but it the combination of line, means many lines together creates the path, then you can use the following method.
For this tutorial suppose you have a div, obj and you want it to move.
First of all you will need a to create path, so as I said earlier your path is made of lines, and line have to ends.
So we will store coordinates in a two dimensional array.
var SIZE = 4; // No of points
var path = new Array(SIZE+1); // one extra point to complete cycle
i=0;
while(i < path.lentgh)
{
path[i] = new Array(2);
i++;
}
// Now we have a two dimensional array
// setting path,
path[0][0] = 0; path[0][1] = 0;
path[1][0] = 0; path[1][1] = 700;
path[2][0] = 1000; path[2][1] = 700;
path[3][0] = 0; path[3][1] = 7;
//completing cycle
path[SIZE][0] = path[0][0];
path[SIZE][1] = path[0][1];
So now we have the path, we are going to use jquery animate function, so we are going to need time also. Now distance between two poits may vary so in stead of setting time, we will set speed and calculate time from it.
SPEED = 3;
var itime = new Array(SIZE);
for(i=0;i < SIZE; i++)
itime[i] = d(i)*SPEED;
Here d(i) is a function defined below that gives the distance between ith ane i+1th point and we are not using speed here its actually inverse of speed. Thus increasing it will slow the animation.
function d(i)
{
// for simplicity
x1 = path[i][0];
x2 = path[i+1][0];
y1 = path[i][1];
y2 = path[i+1][1];
return Math.floor(Math.sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) ))
}
So now we have time and points for animation. So next step is to animate it.
t = 0;
function animateobj(obj)
{
$(obj).animate({left:path[t+1][0], top:path[t+1][1]}, itime[t]);
setTimeout(function(){animateobj(obj);}, itime[t]);
t++;
if(t == SIZE)
t = 0;
}
And you are done, now from your file, just call animateobj method with appropriate id and it will do the animation.
NOTE: set path, itime, SIZE, SPEED, and t as global do not create them inside a function and also you will need jquery which is included in demo.
Click here to download demo.
Hey, if you liked it, please click on ad below...