Animated Pacman - Exercise

Contact Us or call 1-877-932-8228
Animated Pacman - Exercise

Animated Pacman

Duration: 20 to 30 minutes.

In this exercise, you will use setTimeout to draw an animated Pacman like the one pictured below:Pacman

Use of the name and image of "Pacman" is a nod to the Namco-released game Pac-man®.

Open html5-canvas/Solutions/pacman.html in a browser to see the finished example in action.

  1. Open html5-canvas/Exercises/pacman.html in your editor.
  2. Add the JavaScript code necessary to draw and animate the Pacman pictured above. Some of the code is done for you.
    • Draw a filled yellow circle, centered on (255,255) with radius 100.
    • Draw a black triangle on top of the circle: one point of the triangle meets the center of the circle, with the triangle extending off to the right, getting wider; the triangle should extend beyond the circle. The black triangle forms Pacman's mouth.
    • With each call to updateDrawing, change the height of the triangle: the base (the right side) of the triangle should get taller until it reaches the maximum (maxDiff) value; it should then get smaller.
    • Use setTimeout to recursively call updateDrawing, to animate the mouth opening and closing; use a delay value of 25 milliseconds.

Solution:

html5-canvas/Solutions/pacman.html
<!DOCTYPE HTML>
---- C O D E   O M I T T E D ----

<script>
var diff = 0;
var delta = 5;
var maxDiff = 40;

function init() {
	updateDrawing();
}

function updateDrawing() {
	diff = diff + delta;
	if (Math.abs(diff) > maxDiff) {
		delta = delta * -1;
	}
	
	var canvas=document.getElementById("my-canvas");	
	var context = canvas.getContext("2d");
	
	context.fillStyle = "rgb(0,0,0)";
	context.fillRect(0,0,500,500);
	
	context.beginPath();
	context.fillStyle = "rgb(255, 255, 0)";
	context.arc(250, 250, 100, 0, 360);
	context.stroke();
	context.fill();
	
	context.strokeStyle = "rgb(0,0,0)";
	context.fillStyle = "rgb(0,0,0)";
	context.beginPath();
	context.moveTo(250, 250);
	context.lineTo(400, 250 - diff);
	context.lineTo(400, 250 + diff);
	context.closePath();
	context.fill();
	timer = setTimeout(function() {updateDrawing()},25);
} 

---- C O D E   O M I T T E D ----

The first lines of function updateDrawing set diff - the height of the triangle - equal to itself plus delta. If the absolute value of diff becomes greater than maxDiff, we set diff to its negative, swapping its value from negative, to positive, to negative, etc. This is how we accomplish the mouth never getting too wide.

Next we draw (with code that was already provided you) a black rectangle, and draw (with code you wrote) a filled yellow circle inside of (on top of) the black rectangle.

Lastly, we draw the triangle to form the mouth, varying the height of the triangle each time, and use setTimeout(function() {updateDrawing()},25) to recursively call updateDrawing and produce the animation.

Next