#4 - Canvas (animation)

HTML

<canvas id="monCanvas" width="400" height="300">
  Votre navigateur n'est pas compatible HTML5
</canvas>

CSS

canvas {
    outline: solid 1px white;
    background-color: black;
}

html, body {
    width: 100%;
    height: 100%;
    background-color: #DDDDDD;
}

JavaScript

var canvas = document.getElementById("monCanvas");
var ctx = canvas.getContext("2d");

// efface le canvas
function clearCanvas() {
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.restore();
}


// classe Ball
var colors = ["red",
              "lime",
              "blue",
              "cyan",
              "yellow",
              "orange",
              "purple"];

function Ball(x, y) {
    this.x = x || Math.floor( Math.random() * canvas.width );
    this.y = y || Math.floor( Math.random() * canvas.height );
    this.r = Math.floor( Math.random() * 20) + 5;
    this.color = colors[Math.floor(Math.random() * colors.length)];
    
    this.speed = Math.random() * 3 + 1;
    this.direction = Math.random() * Math.PI * 2;
    
    Ball.list.push(this);
};

Ball.list = [];

Ball.prototype.draw = function() {
    ctx.save();
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, Math.PI*2);
    
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.restore();
};

Ball.prototype.step = function() {
    this.x += this.speed * Math.cos(this.direction);
    this.y += this.speed * Math.sin(this.direction);
    
    if(this.x < -this.r) this.x = canvas.width + this.r;
    else if(this.x > canvas.width + this.r) this.x = -this.r;
    if(this.y < -this.r) this.y = canvas.height + this.r;
    else if(this.y > canvas.height + this.r) this.y = -this.r;
    
    if(this.r < 0) Ball.list.splice(Ball.list.indexOf(this), 1);
};

// code d'animation

canvas.addEventListener("mousemove", function(e){
    new Ball(e.pageX, e.pageY);
});

function stepAll() {
    for(var i=0; i<Ball.list.length; ++i) Ball.list[i].step();
}

function drawAll() {
    clearCanvas();
    for(var i=0; i<Ball.list.length; ++i) Ball.list[i].draw();
}

setInterval(function() {
    stepAll();
    window.requestAnimationFrame(drawAll);
}, 1000 / 60);