# Lab 1: Simple Animation with Canvas/JavaScript

• Open Firefox browser and go to http://cs.mvnu.edu
• Click the link to CS Wiki.
• Under Spring 2015 class pages, select CSC3003 Multimedia Programming, and find the link to Lab 1.
• HTML5 has a feature called the <canvas> element, which allows graphics to be displayed on a web page.
• Using JavaScript , web developers can create graphics with animated movement.
• Here is an example showing how an animated runner is produced from a sequence of images: Animated Runner
• Here is a simpler example of animation using HTML5: Bouncing Ball Example
• Using bouncing balls to make something a little more exciting (from Dr. Skon): MVNU Animation
• Follow these steps to learn how to program a bouncing ball animation.

### Step 1 - Draw a ball

• First we need to create a canvas to draw on:
```<body>
<canvas id="myCanvas" width="300" height="300">
</canvas>
</body>```
• A canvas defines a two-dimensional area with a coordinate system measured in units called pixels. A pixel is just one "dot" that may be drawn on the screen.
• Next we can write JavaScript code to draw on this canvas:
```<script>
var context;
function init()
{
context= myCanvas.getContext('2d');
context.beginPath();
// fill objects with blue color
// a color is given by 3 pairs of hexadecimal digits, where the first two digits determine the amount of red,
// the next two digits determine the amount of green, and the last two digits determine the amount of blue.
context.fillStyle="#0000ff";
// This arc function draws a circle of radius 20 centered at the coordinates 100,100 on the canvas
// The parameters of the arc function are: (x, y, r, sAngle, eAngle, direction), where
// x and y are the coordinates of the center of the circle,
// sAngle is the starting angle of the arc (in radians),
// eAngle is the ending angle of the arc (in radians),
// when direction is true the arc is drawn counterclockwise.
context.arc(100, 100, 20, 0, Math.PI*2 ,true);
context.closePath();
context.fill();
}
</script>

<canvas id="myCanvas" width="300" height="300" >
</canvas>
</body>```

• How can we test this out?
• We need a text editor. Go to the Start menu, and find the NotePad++ editor.
• Copy the code above and paste it into the editor.
• Save as "Ball1.html" in your own folder for Lab 1.
• You may test your program either by using the Run menu in NotePad ++, or by finding the file on your Windows desktop and then right click on it, selecting the option to open with FireFox .
• It should draw a simple static ball:

### Step 2 - Move the ball

• Now that we have the circle, let’s try to move it. We’ll replace the constant values of the coordinates in the .arc method (100, 100 — the first two arguments) with variables x and y, which we will then increment by an amount of dx and dy each time the circle is drawn. The new code is shown in blue below.
• Also since we need to redraw the circle repeatedly at the new positions, we’ll move the code into a function called draw() and invoke it every 10 milliseconds using JavaScript ’s setInterval() function.
• Try the code below in the same way, by copying it and pasting it into Notepad++, and name the file "Ball2.html".
```<script>
var context;
var x=100; var y=100; var dx=5; var dy=5;

function init()
{
context= myCanvas.getContext('2d');
setInterval(draw,10);
}

function draw()
{
context.beginPath();
context.fillStyle="#0000ff";
// Draws a circle of radius 20 at the coordinates 100,100 on the canvas
context.arc(x,y,20,0,Math.PI*2,true);
context.closePath();
context.fill();
x += dx;   y += dy;
}

</script>
<canvas id="myCanvas" width="300" height="300" >
</canvas>
</body>```

• We have a problem! The circles are actually forming a line instead of appearing to move accross the screen.

### Step 3 - Erase the old balls!

• The balls merged into a line because each time the draw() function is called, it draws a circle at the new coordinates without removing the old circle.
• To erase the old circles, we’ll need to call the clearRect function right at the start of our draw() function so that it clears out the previous circle before it draws the new one.
```<script>
var context;
var x=100; var y=100; var dx=5; var dy=5;

function init()
{
context= myCanvas.getContext('2d');
setInterval(draw,10);
}

function draw()
{
context.clearRect(0,0, 300,300);
context.beginPath();
context.fillStyle="#0000ff";
// Draws a circle of radius 20 at the coordinates 100,100 on the canvas
context.arc(x,y,20,0,Math.PI*2,true);
context.closePath();
context.fill();
x += dx;
y += dy;
}

</script>
<canvas id="myCanvas" width="300" height="300" >
</canvas>
</body>```

• Try it out by adding the new code in blue to your file named Ball2.html. .... The ball should move across the screen and then disappear.

### Step 4 - bounce the ball inside imaginary walls

• All you need to do is add statements inside the draw() function to check if the values of x and y have gone beyond the canvas dimensions, and if so, we need to reverse the direction of movement by setting values of dx and dy to the negative values.
```<script>
var context;
var x=100; var y=100; var dx=5; var dy=5;

function init()
{
context= myCanvas.getContext('2d');
setInterval(draw,10);
}

function draw()
{
context.clearRect(0,0, 300,300);
context.beginPath();
context.fillStyle="#0000ff";
// Draws a circle of radius 20 at the coordinates 100,100 on the canvas
context.arc(x,y,20,0,Math.PI*2,true);
context.closePath();
context.fill();
// Boundary Logic
if (x<0 || x>300) dx = -dx;
if (y<0 || y>300) dy = -dy;
x+=dx;
y+=dy;
}

</script>
<canvas id="myCanvas" width="300" height="300" >
</canvas>
</body>```
• Edit your code by adding the lines highlighted in blue, and try it out as before.
• This bouncing ball animation illustrates some fundamental methods often used in developing web animations and games, and it can be extended to build a ping-pong game or a block-breaker type of game.

### Step 5

Now try to add or change some more features by changing the appropriate part of the program.

• Change at least 4 of these things:
• the size of the ball,
• the size of the canvas (the invisible boundaries),
• the speed of movement,
• the color of the ball,
• the direction/angle of movement.
• Add at least one more feature to the simulation:
• Change the color of the ball whenever it hits the wall.
• Add a second ball, by using another pair of variables to remember its x and y coordinates, and writing a second group of statements inside the draw function, similar to those that draw the first ball and increment its x and y variables.
• Simulate the effects of gravity and friction (the ball's height decreases with each bounce, and the side to side motion slows down).
• whatever interesting feature you can think of!

### Submission (due Monday 2/9)

Write a short report in Word document with these two parts:

• a list of the features that you changed, and the new feature that you added to the simulation.
• a short paragraph describing what you learned from this exercise, or if you had written a similar program before.
Go to the Moodle course page, and use the link for Lab 1 submission. Attach two files:
• your final HTML code file;
• your report as a Word document.
-- RobertKasper - 2015-02-04
Topic revision: r2 - 2015-02-06 - RobertKasper

TWiki

* Webs

Copyright &© by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback