Author - Web Developer - Educator
RSS Feed

HTML5 Canvas - Bouncing Ball Example

At this point, I'm trying to stay up with HTML5 programming, and I feel like I'm a little behind the times.

So, because I'm in a Python class (via Coursera by Rice University) learning about interactive programming (more specifically, "Pong" was this week's project) and seeing Google's anniversary edition of Breakout, I felt inspired to learn how innovative HTML5 could be, so I looked up some HTML5 references and thought I'd try my hand at it.

Well, I combined by Python experiences and some HTML5 canvas examples and created some ball-bouncing joy. Want a demo? Here's a demo!

Here's a screenshot of it:
Bouncing Ball
I've taken out the clear() function to show it in motion


Even though this is very simple (as compared to some more advanced HTML5 stuff), I thought I'd go ahead and put this here for others to view/use/learn from.

Here's the HTML:
 
<!DOCTYPE html>
 
<html>
 
	<head>
 
		<meta charset='utf-8'/>
 
		<title>Ball Canvas Test</title>
 
		<link href='main.css' rel='stylesheet'/>
 
		<!--[if lt IE 9]>
 
			<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
 
		<![endif]-->
 
		<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js'></script>
 
		<script src='main.js'></script>
 
	</head>
 

 
	<body>
 
		<div id='debug'></div>
 
		<div id='container'>
 
			<canvas id='scene'></canvas>
 
		</div>
 

 
		<footer>
 
			© 2013 - Kyle Perkins
 
		</footer>
 
	</body>
 
</html>
 


Here's the CSS: (this uses a standard Reset CSS, started by Eric Meyers)
 
@import url("//dev.shadowdev.com/reset.css");
 
html, body{
 
	display: block;
 
	text-align: center;
 
}
 
#debug{
 
	position: absolute;
 
	top: 50px;
 
	right: 50px;
 
}
 
canvas{
 
	margin: auto;
 
	display: block;
 
	border: 5px #000 solid;
 
	background-color: #efefef;
 
}
 


And here's the fancy-smancy Javascript:
var canvas, ctx;
 
var circles = [];
 
var circleCount = 4; 
 
var velocity_set = 2;
 

 
function oneorzero(num){
 
	// simple function to randomly get 0 or 1
 
	if (Math.round(Math.random())==1) num *= -1;
 
	return num;}
 

 
function Circle(x,y,radius, color){
 
	// get the information stored for eac ball
 
	this.x = x;
 
	this.y = y;
 
	this.radius = radius;
 
	this.color = color;
 
	var V1 = oneorzero(velocity_set);
 
	var V2 = oneorzero(velocity_set);
 
	// velocity is set as an array so we can have the [x,y] values
 
	// [5,5] means ^,>
 
	// [-5, -5] means V,<
 
	this.velocity = new Array(V1, V2);
 
}
 

 
function clear(){
 
	// clear the screen (prevent "dirty canvas")
 
	ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height);
 
}
 

 
function getrand(){
 
	// function to randomly get a value between 0-255 (one value for R, G, and B each)
 
	return Math.floor((Math.random()*255)+1);
 
}
 

 
function drawCircle(ctx, x, y, radius, color) { // draw circle function
 
//	$('#debug').html("X:"+x+" Y:"+y);
 
//    ctx.fillStyle = 'rgba('+r+', '+g+', '+b+', 1.0)';
 
	ctx.beginPath();
 
	ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
 
	ctx.fillStyle = "rgb("+color+")";
 
	ctx.fill();
 
	ctx.stroke();
 
//    ctx.closePath();
 
}
 

 
function drawScene(){ //main draw function
 
	clear(); //clear the canvas
 
	// this is only for additional draw functionality (testing only)
 
/*	ctx.beginPath();
 
      ctx.arc(canvas.width/2, canvas.height/2, 70, 0, 2 * Math.PI, false);
 
      ctx.fillStyle = 'blue';
 
      ctx.fill();
 
      ctx.lineWidth = 5;
 
      ctx.strokeStyle = '#fc0';
 
      ctx.stroke();
 
*/
 
	
 
	var ball_info ="";
 
	for (var i=0; i 0)
 
		$('#debug').html(ball_info);
 
}
 

 
////////////////////////////////////////
 

 
$(function(){
 
	// call these setup properties upon load
 
	canvas = document.getElementById("scene");
 
	ctx = canvas.getContext('2d');
 

 
	// this is to make sure the canvas spreads across the screen
 
	ctx.canvas.width = window.innerWidth-10; // the canvas has a 5px border
 
	ctx.canvas.height = window.innerHeight-50; // 50 is only for the footer info
 

 
	var circleRadius = 25;
 
	var width = canvas.width;
 
	var height = canvas.height;
 

 
	for (var i = 0; i < circleCount; i++){
 
		// start at random position
 
		var x = Math.random()*(width*.9);
 
		var y = Math.random()*(height*.9);
 
		var r = getrand();
 
		var g = getrand();
 
		var b = getrand();
 
		ballColor = r+","+g+","+b;
 
		// add circle to array
 
		circles.push(new Circle(x,y,circleRadius, ballColor));
 
	}
 
	setInterval(drawScene, 1); // loop drawScene - aka: "draw handler"
 
});
 

 
function animate(ball, canvas, context) {
 
	// this is for adding (aka: "move") the ball based on the velocity increase/decrease
 
	// velocity is an array
 
        ball.x += ball.velocity[0];
 
	ball.y += ball.velocity[1];
 
	
 
        if( (ball.x > (canvas.width - ball.radius)) || (ball.x < (0 + ball.radius))) {
 
		// bounce off left or right wall
 
		ball.velocity[0] *= -1;
 
        }
 
	if ( (ball.y > (canvas.height - ball.radius)) || (ball.y < (0 + ball.radius))){
 
		// bounce off top or bottom wall
 
		ball.velocity[1] *= -1;
 
	}
 

 
	// draw the circles with on the (canvas, x position, y position, radius, color)
 
        drawCircle(ctx, ball.x, ball.y, ball.radius, ball.color);
 
      }


I hope this works for some people learning how to use HTML5 and the "velocity effect"


Tags:#html5 #css #javascript #python #tutorials