vendredi 17 décembre 2010

Explosion - Code source

~/Documents/Aptana Studio Workspace/ParticuleDemo/Particule.js.html
var canvas;
var ctx;
//var trace ;
//var DEBUG = true;
var cw = 800;
var ch = 600;
var lstParts = [];
var nbrParts = 1000;
var p;


setupCanvas = function(){
    canvas =  document.createElement("canvas");
    ctx = canvas.getContext("2d");
    canvas.width = cw;
    canvas.height = ch;
    document.body.appendChild(canvas);
    ctx.setTransform(1,0,0,-1,cw/2,ch/2);
}


Particule = function(x,y) {

    this.x = 0;
    this.y = 0;
    this.prevx = 0;
    this.prevy = 0;
    this.angle = Math.PI;
    this.velx = 0;
    this.vely = 0;
    this.radius = Math.random()*8-4;
    this.color = "rgb(255,0,0)";
    this.dead = false;
    this.age = 0;

    this.draw = function(){
        ctx.strokeStyle = "rgb("+ Math.round(Math.random()*255)+","+
                                   Math.round(Math.random()*255)  + ","+
                                    Math.round(Math.random()*255) + ")";
        ctx.beginPath();
        ctx.moveTo(this.x,this.y);
        ctx.lineTo(this.x+this.velx,this.y+this.vely);
        ctx.closePath();
        ctx.stroke();
    }



    this.update = function(){
        this.age += 1;
        this.x +=  this.velx*0.5;
        this.y +=  this.vely*0.5;
        if (this.age > 100){
            this.dead = true;
        }
    }
}


Emitter = function(){

    this.setup = function(){
        var angle = 0;
        var r = 1;
        var x = Math.round(Math.random()*400-200);
        var y = Math.round(Math.random()*400-200);
        for (i=0; i< nbrParts; i++){
            var p = new Particule();
            p.x = x;
            p.y = y;
            p.velx = r*Math.cos(angle);
            p.vely = r*Math.sin(angle);
            lstParts.push(p);
            angle += Math.random()*6-3;
            r += .05;
        }
    }

    this.draw = function(){
        for (i=0; i< nbrParts; i++){
            lstParts[i].draw();
        }
    }


    this.update = function(){
        for (i=0; i< nbrParts; i++){
            lstParts[i].update();
            if (lstParts[i].dead == true){
                lstParts.splice(i,1);
            }
        }
    }
}

clearRect = function(){
    ctx.fillStyle =   "#00002"
    ctx.fillRect(-400,300,800,-600);
}

startAnimation = function(){
    clearRect();
    if (lstParts.length <= 0){
        p = new Emitter();
        p.setup();
    }
    p.update();
    p.draw();
}

main = function(){
    setupCanvas();
    p = new Emitter();
    p.setup();
    p.draw();
    setInterval("startAnimation()",10);
}

main();

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;...