Monday, September 23, 2013

Simple image animation using javaScript


Creating animation seems kool and yes it is..☺
Its not a big deal. Follow steps shown below to learn how to do so..



1) Make a html file with file extension .htm or .html


2) In head tag, make a script block by using

script type="text/javascript"


3) In body tag-

a) add attribute of body tag- bgcolor="0000FF" onLoad="anime1()"
bgcolor will change background color of page to blue and onLoad event will call anime1 function (defined in script block) after loading of page.


b) Now, inside body tag, add an image using img tag and its attributes as


name="heart" src="http://www.archjrc.com/clipart/images/valentines/heart1.png" style="position: absolute; width: 100px; height: 100px; top:250px; left:600px;"


4) In script block-

a) Declare 4 variables using syntax var widthh=100,heightt=100,leftt=600,topp=250; these variables represent width, height, left margin and top margin of image to be displayed.

b) Make a function, name it anime1, this function is called by onLoad event

c) add following code in anime1 function-

if(widthh<=500)
{
widthh+=2;
heightt+=2;
leftt--;
topp--;
heart.style.width = widthh + "px";
heart.style.height = heightt + "px";
heart.style.left = leftt + "px";
heart.style.top = topp + "px";
setTimeout("anime1()",1);
}
else
{
anime2();
}

This code segment will increase width, height of image by 2 & decrements left,top margin by 1 so that image size gets twice and image keeps in middle of the page

heart.style.width = widthh + "px";
heart.style.height = heightt + "px";
heart.style.left = leftt + "px";
heart.style.top = topp + "px";
these 4 lines assigns dimensions of image to new values


setTimeout("anime1()",1); statement calls itself after every 1 millisecond.
this whole function shows image as swallowing



after completion(max size of image), else block is called and control transfers to anime2 block


d) make another similar function and name it anime2
add code-

if(widthh>=0)
{
widthh-=2;
heightt-=2;
leftt++;
topp++;
heart.style.width = widthh + "px";
heart.style.height = heightt + "px";
heart.style.left = leftt + "px";
heart.style.top = topp + "px";
setTimeout("anime2()",1);
}
else
{
anime1();
}

this code is exactly opposite of previous one, width,height decreases by 2 and top,left increases by 1 until width of image is not equal to zero


this will in last calls anime1 function.



5)Therefore, anime1 and anime2 functions calls each other and we get a swallowing-shrinking image..

Have fun O:)