Particle Systems: Fireworks

Haz clic en el canvas. Este muestra un uso básico de partículas, creando 200 nuevas partícula cuando se hace aprieta el botón del mouse, base del Sistema de Partículas.

El código para crearle se encuentra más abajo.

Canvas not suported by your browser.

HTML:

<canvas id="canvasg" width="600" height="400">
  Canvas not suported by your browser.
</canvas>

Javascript:

// fireworks.js

var canvasg,ctx;
var particles=new Array();

window.onload=function(){
	canvasg=document.getElementById('canvasg');
	ctx=canvasg.getContext('2d');
	setInterval(repaint,50);
}

function repaint(){
	ctx.fillStyle='#000';
	ctx.fillRect(0,0,canvasg.width,canvasg.height);
	
	for(var i=0;i<particles.length;++i){
		if (particles[i].maxage > 0)
			{
				particles[i].x+=particles[i].speed*Math.cos((Math.PI/180)*particles[i].angle);
				particles[i].y+=particles[i].speed*Math.sin((Math.PI/180)*particles[i].angle);
				particles[i].maxage--;
				// Draw
				ctx.fillStyle=particles[i].color;
				ctx.beginPath();
				ctx.arc(particles[i].x,particles[i].y,particles[i].diameter/2,0,Math.PI*2,true);
				ctx.closePath();
				ctx.fill();
			}
			else
				particles.splice(i,1);
	}
	ctx.fillText('P: '+particles.length,10,10);
}

function random(n){
	return Math.random()*n;
}

function randomColor(){
	return '#'+clr2hex(random(255))+clr2hex(random(255))+clr2hex(random(255));
}

function clr2hex(n){
	var n=parseInt(n,10);
	if(isNaN(n)) return '00';
	n=Math.max(0,Math.min(n,255));
	return '0123456789ABCDEF'.charAt((n-n%16)/16)+'0123456789ABCDEF'.charAt(n%16);
}

function Particle(x,y,diameter,maxage,speed,angle,color){
	this.x=0;
	this.y=0;
	this.diameter=2;
	this.age=0;
	this.maxage=1;
	this.angle=0;
	this.speed=1;
	this.color='#fff';

	this.set=function(x,y,diameter,maxage,speed,angle,color){
		if(color!=null){
			this.x=x;
			this.y=y;
			this.diameter=diameter;
			this.maxage=maxage;
			this.speed=speed;
			this.angle=angle;
			this.color=color;
		}
	}
	this.set(x,y,diameter,maxage,speed,angle,color);
}

document.addEventListener('click',function(evt){
	var mousex=evt.x-canvasg.offsetLeft;
	var mousey=evt.y-canvasg.offsetTop;
	for(var i=0;i<200;i++)
		particles.push(new Particle(mousex,mousey,2,random(80),random(5),random(360),randomColor() ));
},false);

Regresar