Bouncing ball on Canvas javascript.

This is a simple html skeleton to hold the canvas element.

<!DOCTYPE HTML>
<html lang="en">
	<head>
		<title>Moving Ball</title>
		<script type="text/javascript" src="bouncing.js"></script>
	</head>
	<body>
		<canvas id="canvas" width="600" height="400">
			<p>Your browser does not support the canvas element.</p>
		</canvas>
	</body>
</html>

This is the javascript code to move the ball.

var FPS = 30;
var x   = 0;
var y   = 0;
var xDirection = 1;
var yDirection = 1;
var image = new Image();
image.src = 'football.png';
var canvas = null;
var ctx2D  = null;

window.onload = function() {
    canvas = document.getElementById('canvas');
    ctx2D  = canvas.getContext('2d');
    setInterval(draw, 1000/FPS);
}

function draw() {
    ctx2D.clearRect(0, 0, canvas.width, canvas.height);
    ctx2D.drawImage(image, x, y);
    x += 1 * xDirection;
    y += 1 * yDirection;

    if (x >= 450) {
        x = 450;
        xDirection = -1;
    } 
    else if (x <= 0) {
        x = 0;
        xDirection = 1;
    }

    if (y >= 250) {
        y = 250;
        yDirection = -1;
    } 
    else if (y <= 0) {
        y = 0;
        yDirection = 1;
    }

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s