Course notes 22
syllabus | schedule | exercises | assignments | class notes | resources | students | ARTC courses

Canvas Animation

Outside of user interaction,animation on the canvas is accomplished by using javascript's setTimeout() and setInterval() to mimic the effects of a frame rate. Each time the interval executes:

  1. the canvas is cleared
  2. the content is redrawn

Clearing the entire canvas is very simple. The context.clearRect() command allows one to erase a portion of canvas as designated. To clear the whole canvas we pass a rectangle that covers the entire width and height.

In order for the contents to change some variable has to be augmented every iteration. This can be accomplished within the actual drawing function utilizing some form of randomization or external input, or by incrementing values initialized outside the function

The first example animates a circle expanding and fading out. The radius and alpha are initialized outside then function. Then, every iteration, the function checks the values and either increments or resets them.

function init(){
	setInterval(draw_ex01,20);
}

var radius = 10;
var alpha = 1;

function draw_ex01(){
    var canvas = document.getElementById('ex01');
    var ctx = canvas.getContext('2d');
    ctx.clearRect(0,0,canvas.width,canvas.height);
    
    ctx.save();
    
    ctx.translate(canvas.width/2,canvas.height/2);
    ctx.fillStyle = 'rgba(0,100,200,'+alpha+')';
    ctx.beginPath();
    ctx.arc(0,0,radius,0,Math.PI*2,false);
    ctx.fill();
    
    if(radius >= 100) {
        radius = 0;
    } else {
        radius+=1;
    }
    
    if(alpha <= 0){
        alpha=1;
    } else {
        alpha-=.01;
    }
    
    ctx.restore();
}

The second example animates a circle rotating around the origin. The coordinates are derived from the static radius and the incremented angle using sin and cos. Remaining in radians, every iteration the angle is checked against Math.PI*2 and either reset to 0 or incremented by .05

function init(){
	setInterval(draw_ex02,30);
}

var angle = 0;
var radius = 100;

function draw_ex02(){
    var canvas = document.getElementById('ex02');
    var ctx = canvas.getContext('2d');
    ctx.clearRect(0,0,canvas.width,canvas.height);
    
    ctx.save();
    
    ctx.translate(canvas.width/2,canvas.height/2);
    
    var x = radius * Math.cos(angle);
    var y = radius * Math.sin(angle);
    
    ctx.fillStyle = 'rgb(0,100,200)';
    ctx.beginPath();
    ctx.arc(x,y,10,0,Math.PI*2,false);
    ctx.fill();
    
    if(angle >= Math.PI*2){
        angle = 0;
    } else {
        angle += .05;
    }
    
    ctx.restore();
}