# Canvas Animation: Random Bounce In a Box

In the last article I demonstrated literally straightforward animation, moving a square from one side of the canvas drawing element to the other. In this piece, I’ll show continuous motion of a circle in many different directions, a useful lesson in how to develop a complete JavaScript canvas animation:

## Preparing the Canvas

The page starts with a `<canvas>` element:

``<canvas id="drawspace" width="800" height="500"></canvas>``

I’ll also style the element, and make it responsive:

``````#drawspace {
background: #000;
width: 100%;
}``````

The JavaScript, at the bottom of the page, starts by creating a shortcut to the drawing context of the canvas, then sets up a constant for the radius of the circle that will be drawn on it, together with variables that determine the circle’s initial position:

``````const ctx = drawspace.getContext("2d"),
circRad = 100;
let x = 150,
y = 200;
ctx.fillStyle = "yellow";``````

Drawing a circle in `<canvas>` is more complicated than drawing a rectangle: we need to start a path, create a closed arc, then end the path.

``````function drawCirc() {
ctx.beginPath();
ctx.arc(x,y,circRad,0,2*Math.PI,true);
ctx.closePath();
ctx.fill();
}
drawCirc();``````

The parameters of the `arc` method can be a little confusing: the `0` defines the starting point for the arc, while the calculation at the end provides the closing point in rads. The `true` parameter defines the direction of the arc (clockwise or counter-clockwise) not relevant for making a closed circle, but a required parameter all the same.

## Bounce

Right now, the function draws the circle at a fixed position. If we want to animate the circle, we need to change the value of `x` and/or `y` over time. And if we don’t want the circle to drift off the side of the canvas, we need to detect when the circle hits the edge, reversing the direction of travel when it does so. I’ll start by changing the motion of the ball on the`x` axis first.

Before we begin, we need to determine how much the ball moves during each moment of the animation. That’s controlled by two variables added to the start of the script:

``````let x = 150,
y = 200,
dx = 2,
dy = 2;``````

The `drawCirc` function changes to:

``````function drawCirc() {
ctx.clearRect(0, 0, drawspace.width, drawspace.height);
ctx.arc(x,y,circRad,0,2*Math.PI,true);
if (x < 0 || x > drawspace.width) {
dx=-dx;
}
x+=dx;
window.requestAnimationFrame(drawCirc);
}``````

The function needs some explanation:

• the `clearRect` cleans the canvas space before it is drawn on.
• bouncing ahead, the `x` variable has the value of `dx` added to it.
• just before that, there is a test: if `x` is less than `0` or greater than the width of the canvas, the sign of `dx` is flipped, equivalent to multiplying it by `-1`: if the value of `dx` was positive, it turns negative, and if it was negative, it turns positive.

The result is that the ball will “bounce” between the vertical edges of the canvas: when it hits the right wall, the flipped sign of `dx` will result in `x` being subtracted from, heading the ball to the left.

One problem is that the ball will go too far: half of the ball will disappear over each edge, since the circle’s position is always measured from its center. We can correct that, using a variable we defined earlier:

``````if (x < circRad || x > drawspace.width - circRad) {     …
}``````

We can use the same approach for vertical movement. The function changes to:

``````function drawCirc() {
ctx.clearRect(0, 0, box.width, box.height);
ctx.drawImage(img, x, y, img.width, img.height);
if (x < circRad || x > drawspace.width - circRad) {
dx=-dx;
}
if (y < circRad || y > drawspace.width - circRad) {
dy=-dy;
}
x+=dx;
y+=dy;
window.requestAnimationFrame(drawCirc);
}``````

The result is a animated ball bouncing randomly inside the area of the canvas. The angle of those bounces and the speed of travel can be changed by altering the value of `dx` and `dy`.

This code can be used in many different ways, as you can see in the associated CodePen demo.

Since you know when the ball hits any of the internal walls of the canvas area, you could do anything at that moment: change the color of the ball, start it in a random location, play a sound through the Web Audio API, etc. I’ll be demonstrating a few of those possibilities in the next article.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/BLPpxq