Categories
Articles

HTML5 Canvas Circular Rotation Animation Example

Started dabbling with the HTML5 canvas to create animations. This example animates a filled circle rotating around the center point. I kept the example as simple as possible while anticipating some of the coding design required for a more complex build.

A build on this example that accepts user keyboard input to control the animation play, start, stop, direction and speed is available in this follow up post.

Foundation HTML5 Animation with JavaScript
Learn More

One item that is more sophisticated is that the canvas tag is dynamically created in the Javascript code on lines 35 – 40. This is not necessary as the tag could be inserted into the html and referenced with an id.

Another is including JQuery from the Google CDN. Listening to the body onLoad method is a substitute.

Also I included the script tag after the html content. The script tag could go in the head section. Placing after the html in the body tag allows html content to load and style before the script code is parsed.

Demo

Source

This is the html5 head section. There is an internal style on lines 8 – 17 for the html in the document. Line 4 brings in JQuery from the Google CDN. Line 20 is the display title for the page.

<!DOCTYPE HTML>
<html>
<head>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<title>HTML5 Canvas Circular Movement Based Animation</title>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style type="text/css">
	body {
		font-family:Arial, Helvetica, sans-serif;
		font-size:12px;
	}
	#titleDiv{
		font-family:Verdana, Geneva, sans-serif;
		font-size:16px;
	}
</style>
</head>
<body>
<div id="titleDiv">HTML5 Canvas Circular Movement Based Animation</div>
<script type='text/javascript'>

The animation key variables are definite and initialized here to keep as many bare numbers out of the code as possible.

The canvas has a border. So there is some computational needs on lines 26-27 to take the border out in computing the center point. May not make a difference in this example, but is helpful for a future example where that boundary is important.

	var CANVAS_WIDTH = 480;		// Canvas width
	var CANVAS_HEIGHT = 480;	// Canvas height
	var FPS = 30;				// Frames per second
	// Canvas center points adjusting for stroke.
	var canvasCenterX = (CANVAS_WIDTH - 1) / 2;
	var canvasCenterY = (CANVAS_HEIGHT - 1) / 2;
	// Radius of the rotation
	var radius = 200;
	// Speed of movement
	var speed = .05;
	// Angle for computing cosine and sin.
	var angle = 0;
	// 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');

[ad name=”Google Adsense”]
This defines the object that moves in the circular rotation. The name player is arbitrary but hints at a way to define objects for a game.

Later we will see the animation loop. The animation loop call the draw function of the items in the animation. So you see the draw function for the player on line 49. This is how to draw a filled circle with a border using the html5 canvas api.

Additionally each object has an init function that is called to initialize the animation objects. For this example the init function for the player object is empty. It could be used for an initial placement of an object for example.

Line 59 shows the master init function that would call all necessary component init functions.

	
	// Object defining the player we are rotating.
	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();
	  	},
		init: function()
		{
		}
	};	
	// Initialize game
	function init()
	{
		player.init();
	}

[ad name=”Google Adsense”]
The update function updates the model data. The animation timer will call this for each animation interval.

Primarily the computations are a right triangle from the center point to the place for the player object to be drawn based on the current angle. This is the x and y where the leg and hypotenuse are based on the angle.

	// Update the model data.
	function update() 
	{  
		// Compute the triangle coordinates from the center of rotation
		player.x = canvasCenterX + Math.cos(angle) * radius;
		player.y = canvasCenterY + Math.sin(angle) * radius;
		// Keep moving the rotation. Use -= for reverse rotation.
		angle += speed;
	}

This is the view being drawn. It draws anything that has to do with the overall canvas. However you could make that a class or object like player and give it a draw method.

Line 85 shows the player draw method being called.

	// 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();
	}

[ad name=”Google Adsense”]
This is the start of the script and the heart of the animation. Once JQuery is ready the animation init function is called. Next a Javascript interval is started to call the animation update method to update the data and then the animation draw method to redraw the view.

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

</script>
</body>
</html>