Bouncing Ball Using Raphaël Javascript Library

Today’s personal project was to create a simple bouncing ball using the Raphaël JavaScript library.  This is such a powerful library, if you’re not familiar with it you should check it out.

The Ball

Lots of hang time.

The Code

This short script creates and animates the ball and the shadow. When placed in the <head> of the document the bouncy ball animation will be inserted into a <div id="bouncy_ball"></div>. Remember to include the latest versions of Raphaël and jQuery in the <head> of the document before this script.

<script>
$(document).ready(function() {
	var paper = Raphael(document.getElementById("bouncy_ball"), 100, 200);
	var bouncy_ball = paper.circle(30, 115, 10).attr("gradient", "r#293df7-#1e2dbd");
	var bouncy_shadow = paper.ellipse(30, 120, 8, 8).attr({fill: "#484643", stroke:"none"}).toBack();
	function bounce_up() {
		bouncy_ball.animate({cy: 115}, 500, '<', bounce_drop);
		bouncy_shadow.animate({rx:8,ry:8,fill:"#484643"}, 500, '<');
	}	
	function bounce_drop() {
		bouncy_ball.animate({cy: 15}, 600, '>', bounce_up);
		bouncy_shadow.animate({rx:25,ry:10,fill:"#e7e7e7"}, 600, '>');
	}
	bounce_drop();
});
</script>

Leave a Reply