Animation

We Can Actually Make Our Drawings Move!

Animation

  1. Clear canvas
  2. Draw image
  3. Move position of image
  4. Go back to step #1

(think of a flip book!)

Clearing the Canvas

context.clearRect(0, 0, sketch.offsetWidth, sketch.offsetHeight);

Repeatedly Drawing

To repeatedly draw and clear out images, we can use a built-in function called setInterval - it takes two parameters:

// will repeatedly call animate every 10ms
setInterval(animate, 10);

Velocity and Position

In order to keep track of how our drawing moves, will need to use a few variables:

An Object

The Animate Function

Let’s create a rectangle that travels across the screen horizontally.

Animating a Rectangle

document.addEventListener('DOMContentLoaded', main);

var sketch;
var context;
var rectangle = {'x':0, 'y':100};
var dx = 1;
var fps = 10;

function main() {
	sketch = document.getElementById('sketch');
	context = sketch.getContext("2d");
	setInterval(animate, fps);
}

function animate() {
	context.clearRect(0, 0, sketch.offsetWidth, sketch.offsetHeight);
	context.fillRect(rectangle.x, rectangle.y, 120, 40);
	rectangle.x = rectangle.x + dx;
}

Boundaries

We can use sketch.offsetWidth and sketch.offsetHeight to determine horizontal and vertical boundaries.

If the position of our drawing reaches these boundaries, change its velocity by multiplying by -1… and setting the position appropiately…

See this example in action!

(Click the link above. Arrow right when ready to proceed...)

Let’s create a rectangle that bounces back and forth horizontally.

Rectangle Bounce (Part #1...)

document.addEventListener('DOMContentLoaded', main);

var sketch;
var context;
var rectangle = {'x':0, 'y':100, 'w':120, 'h':40};
var dx = 3;
var fps = 10;

function main() {
	sketch = document.getElementById('sketch');
	context = sketch.getContext("2d");
	setInterval(animate, fps);
}

function animate() {
	context.clearRect(0, 0, sketch.offsetWidth, sketch.offsetHeight);
	context.fillRect(rectangle.x, rectangle.y, 120, 40);

	rectangle.x = rectangle.x + dx;
	

Rectangle Bounce (Part #2)



	if (rectangle.x > sketch.offsetWidth - rectangle.w - dx) {
		dx = dx * -1;
		rectangle.x = offsetWidth;
	} else if (rectangle.x < 0 + dx) {
		dx = dx * -1;
		rectangle.x = 0;
	}
}

See this example in action!

(Click the link above...)