Skip to content

Instantly share code, notes, and snippets.

@jmhobbs
Created August 12, 2011 21:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jmhobbs/1143088 to your computer and use it in GitHub Desktop.
Save jmhobbs/1143088 to your computer and use it in GitHub Desktop.
Simple JavaScript Particles
<html>
<head>
</head>
<body>
<canvas id="base" width="500" height="500" style="border: 1px solid #444; background: #000;"></canvas>
<script>
var elem = document.getElementById( 'base' );
var context = elem.getContext( '2d' );
var Sprite = function () {
this.size = 20;
this.radius = Math.floor( this.size / 2 );
this.p_x = Math.floor( Math.random() * 500 );
this.p_y = Math.floor( Math.random() * 500 );
this.x_speed = Math.floor( Math.random() * 7 ) - 3;
this.y_speed = Math.floor( Math.random() * 7 ) - 3;
if( this.x_speed == 0 && this.y_speed == 0 ) { this.x_speed = 1; }
this.clear = function () {
context.clearRect( this.p_x, this.p_y, this.size, this.size );
};
this.draw = function () {
this.radgrad = context.createRadialGradient( this.p_x + this.radius, this.p_y + this.radius, 0, this.p_x + this.radius, this.p_y + this.radius, this.radius );
this.radgrad.addColorStop( 0, 'rgba(255,255,255,255)' );
this.radgrad.addColorStop( 1, 'rgba(255,255,255,0)' );
context.fillStyle = this.radgrad;
context.fillRect( this.p_x, this.p_y, this.size, this.size );
};
this.move = function () {
this.p_x = this.x_speed + this.p_x;
this.p_y = this.y_speed + this.p_y;
};
this.draw();
}
var ParticleManager = function ( count ) {
this.sprites = [];
for( var x = 0; x < count; ++x ) {
this.sprites.push( new Sprite() );
}
this.start = function () {
var mgr = this;
this.interaval = setInterval( function () { mgr.move(); }, 50 );
};
this.move = function () {
for( var i in this.sprites ) {
this.sprites[i].clear();
this.sprites[i].move();
}
for( var i in this.sprites ) {
this.sprites[i].draw();
}
};
}
var pm = new ParticleManager( 200 );
pm.start();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment