Today, we'll see how to implement a bouncing ball in javascript. The ball will bounce all around the page and we will also introduce a gravity factor to make the ball slowly come to rest. The technique is what is important here. It can then be used in any kind of moving-object animation. What we will be doing is take an image of a ball (with a transparent background, obviously) and change its positions so quickly so as to give it the effect of a moving ball. The changing of the position will be done using CSS. CSS itself will be changed using our favorite scripting language, javascript. Checkout Working Example here We'll take "x" and "y" as the coordinated of the ball. Then, "h" and "v" will be the displacement per move in the horizontal and vertical directions respectively. "g" with an initial value of 2 will be the gravity value. You can increase this to higher values when you want the ball to settle down. Or, you can implement a Key Listener event in which case the gravity increases when you press a key. This is what we will be doing here. Now that we are clear on the variables, all that is left to do is to look at the code. It is very simple to understand. HTML: <html> <head> <style type="text/css"> .b {position:absolute; left:0px; top:0px; width:50px; height:50px;} </style> <SCRIPT language="javascript"> <!-- var x = 0; var y = 0; var h = 10; var v = 2; var g = 2; var r = 0; var q = 0; var gg = 0; var Netscape=(navigator.appName.indexOf("Netscape") != -1); if(Netscape){document.captureEvents(Event.KEYPRESS);document.onkeypress = testKey;} function moveball() { var e = document.getElementById('ball'); v=v+g;r=q;q=y;if(y==r&&y>394&&g==5)return; x=x+h;y=y+v; if(x>752+(Netscape)*28){x=752+(Netscape)*28;h=h*-1;} if(y>408-(Netscape)*12){y=408-(Netscape)*12;v=v*-1;} if(x<0){x=0;h=h*-1;} if(v==-26&&gg==5){gg=0;g=5;} e.style.top=y + 'px'; e.style.left=x + 'px'; t=setTimeout("moveball()",0); } function testKey(){gg=5;} // --> </script> </head> <body onLoad="moveball();" onKeyPress="testKey();"> <p>PRESS A KEY TO SEE GRAVITY SLOWLY STOP THE BALL (otherwise it won't stop).</P> <div id="ball" class="b"><img src="http://cache.g4estatic.com/bouncing-ball/ball.jpg" width="50" height="50"></div> </body> </html> Now that was pretty easy, right? Just some basic programming skills with Javascript and CSS and you can make numerous animations just like this one. Of course, you can tweak the code and make it for multiple images or for whatever animation you would like to put on your website
If you liked this article do nominate this article for Article of the month - Sep 2010 Before 15th of October 2010.
I made a program for bouncing ball but i couldn't make it better. it is run correct but i need clew to how control the numbers of movement of the ball.
Article selected for voting for Article of the month - Sep 2010. Cast your vote now before October 27th, 2010