dimanche 5 décembre 2010

Code source de l'animation 'Bouncing'


~/Untitled.html
<!DOCTYPE>
<html>
<body>
<canvas id="canvas" /><br />
<script type="text/jscript" >

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var cw = 600;
var ch = 600;

canvas.width = cw;
canvas.height = ch;

random = Math.random;

// On définie un objet Particule
// et ses attributs.
Particule = function(){
                this.x = 0;
                this.y = 0;
                this.r = 0;
                this.vx = 0;
                this.vy = 0;
                this.dt = 0.1;
};

// Méthode partagée par tous
// les objets de type Particule
// L'appel de cette méthode permet d'initialiser
// les attributs définis dans la classe de base
Particule.prototype.init = function(){
    this.x = cw/2;
    this.y = ch/2;
    this.r = random()*40+3;
    this.vx = random()*20-5;
    this.vy = random()*20-5;
}

// Méthode partagée par tous
// les objets de type Particule
// L'appel de cette méthode permet 
// de visualiser une particule.
Particule.prototype.draw =  function(){
    ctx.beginPath();
    ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false)
    ctx.closePath();
    ctx.shadowOffsetX = 5;
    ctx.shadowOffsetY = 5;
    ctx.shadowBlur    = 4;
    ctx.shadowColor   = 'rgba(255, 0, 0, 0.5)';
    ctx.fillStyle   = 'rgba(255, 130, 0, 0.5)';
    ctx.fill();
}

// Méthode partagée par tous
// les objets de type Particule
// L'appel de cette méthode permet 
// de mettre à jour les positions et 
// vitesses de chaque particule
Particule.prototype.update = function(){
    if (this.x > cw) this.vx *= -1;
    if (this.x < 0) this.vx *= -1;
    if (this.y < 0) this.vy *= -1;
    if (this.y > ch) this.vy  *= -1;
    this.x += this.vx*this.dt;
    this.y += this.vy*this.dt;
}

// Liste contenant les particules
lstPart = [];

// Nombre de particules
nbrPart = 55;


// On crée les particules et on les ajoute
// à la liste
for (var i = 0; i < nbrPart; i++){
    p = new Particule();
    p.init();
    lstPart.push(p)
}

// Procédure appelé  à interval régulier
updateScene = function() {
    ctx.clearRect(0,0,cw,ch)
    for (var i=0; i< nbrPart; i++){
        lstPart[i].update();
        lstPart[i].draw();
    }
}

// La procédure 'updateScene' est appelée
// 30 fois par seconde
setInterval('updateScene()',30);
</script>

</body>
</html>


Aucun commentaire:

Enregistrer un commentaire

Explosion - Code source

~/Documents/Aptana Studio Workspace/ParticuleDemo/Particule.js.html var canvas; var ctx; //var trace ; //var DEBUG = true;...