(click anywhere to close)
OPEN MENU

[Canvas] Animation

category: Website | course: Canvas | difficulty:
IN PRINT
QUICK CONTENTS:Intro

Because canvas doesn’t work with individual objects, it doesn’t have support for animations in the usual way. With CSS, for example, you can select an element and change one of its properties over time, and you have an animation. With canvas, you have to constantly redraw the canvas with the next frame of the animation. This means that you need two things:

  • A function containing a set of methods that draw what you want, depending on which frame you’re on.
  • A loop that calls this function at regular intervals

Luckily, JavaScript doesn’t leave you in the dark completely, and has a special method for calling a function at regular intervals:

requestAnimationFrame(function)

This tries to call function at 60 FPS (frames per second), or every 1/60th of a second. It’s perfectly possible though that your function is too heavy for the computer and can’t be executed that quick, in which case the JavaScript just tries to call the function as quickly as possible. Another great advantage of this method is that it stops executing if you’re not focused on the canvas. So, if you move to another tab, it stops wasting resources on keeping the animation running.

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

requestAnimationFrame(animate);
var frame = 0;
var box = {x:0, y:20, colour:'red', width:30, height:30};

function animate() {
	//Clear whole canvas
	ctx.clearRect(0, 0, canvas.width, canvas.height);

	//Increase frame count
	frame++;

	//Make box slide to the right
	box.x += 0.5;

	//Redraw the box using new settings
	drawBox();

	//After 120 frames, reset the box
	if(frame == 120) {
		box.x = 0;
		frame = 0;
	}

	//Request our next frame!
	requestAnimationFrame(animate);
}

function drawBox() {
	ctx.beginPath();
	ctx.rect(box.x, box.y, box.width, box.height);
	ctx.fillStyle = box.colour;
	ctx.fill();
}

The example is really just an example in this case; it’s up to you how you animate things. But, the usual practice is to update a set of global variables each frame, and use those variables to determine what must be drawn (and how) every frame.

If you want to learn more about this method of animating and creating a dynamic canvas, I suggest looking at the course on HTML5 games.

CONTINUE WITH THIS COURSE
[Canvas] CompositesNo next post :(
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)