Categories
Articles

HTML5 Canvas Bobbing Circle Animation Demonstrating Sine Wave Movement

This is an example of using the HTML5 canvas and using JavaScript Math.sin to produce a bobbing animation of a circle.

Demo

Download Source

This example is in one HTML document that contains all the JavaScript.

Foundation HTML5 Animation with JavaScript
Learn More

JQuery is included only to detect when the document is ready and start the timer for the animation. The timer calls an update function which updates the data values for the items on the canvas. In this case it is just the animated object. The timer also calls the draw function that calls the animated object’s draw function.

I am using the Google CDN for JQuery.

This example adds the canvas node to the body dynamically in JavaScript and is just a technique. You could include the canvas tag statically.

You can view the full html file at the end of the post. I will excerpt parts to explain what is going on inside the code.

[ad name=”Google Adsense”]

Once JQuery is ready the animation timer is started. The timer calls the update and draw methods.

	// JQuery ready
	$(function() 
	{
		// Start here.
		// Timer for animation.
		setInterval(function() 
		{
			update();
			draw();
		}, 1000/FPS);
	});

This is the draw method. It simply clears the canvas, draws the canvas background and border, and then calls the draw method of the animation object called player.

	// Draw the views
	function draw() 
	{
		canvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
		canvas.strokeStyle = "red";
		canvas.strokeRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
		canvas.fillStyle = "#ccc";
		canvas.fillRect(.5, .5, CANVAS_WIDTH-1, CANVAS_HEIGHT-1);
		player.draw();
	}

The model animation data is maintained in the update function. There is the angle and the player x and y positions to update.

The player x value is the horizontal center of the canvas. That does not change in this example.

Line 57 computes the player y value. The values of 1 to -1 are computed from the angle using the Math.sin function. The angle variable increments infinitely. The Math.sin function uses the angle values as real possible angles in geometry you are accustomed to using.

The yRange value of 200 multiplied by Math.sin(angle) results in values between -200 and 200.

Adding the result to canvasCenterY, the vertical center of the canvas, creates the y value plus or minus the vertical center of the canvas.

	// Update the model data.
	function update() 
	{
		// Coordinate for x is center canvas width.
		player.x = canvasCenterX;
		// Coordinate y is the sine of the angle 
		// for a positive or negative percentage of the range 
		// using the canvas vertical for the center of the range.
		player.y = canvasCenterY + Math.sin(angle) * yRange;
		// Angle changed by speed.
		angle += speed;
	}

[ad name=”Google Adsense”]
This is the object that is being animated. It contains some basic properties for a circle and contains a method for drawing.

	var player = {
		color: "#00A",
		x: 0,  	// Starting x
		y: 0,	// Starting y
		width: 32,
		height: 32,
		radius: 20,
		draw: function() // Draw the player.
		{
			canvas.fillStyle = this.color;		
			canvas.beginPath();  
			canvas.arc(this.x,this.y,this.radius,0,Math.PI*2,true); 
			canvas.fill();
			canvas.lineWidth = 5;
    		canvas.strokeStyle = "black";
    		canvas.stroke();
	  	}
	};	

The entire HTML document for your convenience to view and copy.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<title>HTML5 Canvas Based Animation Sine Wave Movement Using Bobbing Circle</title>
</head>
<body>
<script type='text/javascript'>
	var CANVAS_WIDTH = 480;		// Canvas width
	var CANVAS_HEIGHT = 480;	// Canvas height
	var FPS = 30;				// Frames per second
	// Canvas center points adjusted for stroke.
	var canvasCenterX = (CANVAS_WIDTH - 1) / 2;
	var canvasCenterY = (CANVAS_HEIGHT - 1) / 2;
	// Speed of movement
	var speed = .05;
	// Angle for computing cosine and sin.
	var angle = 0;
	// Range of the vertical movement.
	var yRange = 200;
	// Create a canvas element variable.
	var canvasElement = $("<canvas width='" + CANVAS_WIDTH + 
	  "' height='" + CANVAS_HEIGHT + "'></canvas");
	// Reference to the canvas 2d context.
	var canvas = canvasElement.get(0).getContext("2d");
	// Dynamically append a canvas element to the body tag.
	canvasElement.appendTo('body');	
	// Object defining the player we are moving.
	var player = {
		color: "#00A",
		x: 0,  	// Starting x
		y: 0,	// Starting y
		width: 32,
		height: 32,
		radius: 20,
		draw: function() // Draw the player.
		{
			canvas.fillStyle = this.color;		
			canvas.beginPath();  
			canvas.arc(this.x,this.y,this.radius,0,Math.PI*2,true); 
			canvas.fill();
			canvas.lineWidth = 5;
    		canvas.strokeStyle = "black";
    		canvas.stroke();
	  	},
	};	
	// Update the model data.
	function update() 
	{
		// Coordinate for x is center canvas width.
		player.x = canvasCenterX;
		// Coordinate y is the sine of the angle 
		// for a positive or negative percentage of the range 
		// using the canvas vertical for the center of the range.
		player.y = canvasCenterY + Math.sin(angle) * yRange;
		// Angle changed by speed.
		angle += speed;
	}
	// Draw the views
	function draw() 
	{
		canvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
		canvas.strokeStyle = "red";
		canvas.strokeRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
		canvas.fillStyle = "#ccc";
		canvas.fillRect(.5, .5, CANVAS_WIDTH-1, CANVAS_HEIGHT-1);
		player.draw();
	}
	// JQuery ready
	$(function() 
	{
		// Start here.
		// Timer for animation.
		setInterval(function() 
		{
			update();
			draw();
		}, 1000/FPS);
	});
</script>
</body>
</html>