Particle field with .eachParticleDo
by SHELDON PASCIAK
HTML
<div id="field-area"></div>
CSS
html, body {
height: 100%;
font-family: sans-serif;
}
#field-area {
left: 0;
top: 0;
width: 100%;
height: 100%;
position: absolute;
}
body, h1 {
margin: 0;
padding: 0;
}
JavaScript
// -------------------------- Field -------------------------- //
function Field( elem, particleCount, maxDisplacement ) {
this.elem = elem;
particleCount = 444;//particleCount || 1009;
this.width = this.elem.offsetWidth;
this.height = this.elem.offsetHeight;
this.spacing = Math.floor( Math.sqrt( document.body.offsetWidth * document.body.offsetHeight / particleCount ) );
this.maxDisplacement = maxDisplacement || this.spacing;
this.cols = Math.floor( this.width / this.spacing );
this.rows = Math.floor( this.height / this.spacing );
// make some particles
this.particles = [];
var particle, x, y;
var frag = document.createDocumentFragment();
for ( var row=0; row < this.rows; row++ ) {
for ( var col=0; col < this.cols; col++ ) {
x = ( col + 0.5 ) * this.spacing;
y = ( row + 0.5 ) * this.spacing;
particle = new Particle( x, y, this.spacing, this.maxDisplacement );
this.particles.push( particle );
frag.appendChild( particle.elem );
}
}
this.elem.appendChild( frag );
this.elem.addEventListener( 'mousemove', this, false );
}
// allows for mousemoveHandler to be triggered after mousemove event
Field.prototype.handleEvent = function( event ) {
var handler = event.type + 'Handler';
if ( this[ handler ] ) {
this[ handler ]( event );
}
};
Field.prototype.mousemoveHandler = function( event ) {
var point = {
x: event.pageX,
y: event.pageY
};
this.eachParticleDo( 'reachFor', point );
};
Field.prototype.eachParticleDo = function( methodName ) {
var particle;
// pass in any other arguments after methodName
var args = Array.prototype.slice.call( arguments, 1 );
for ( var i=0, len = this.particles.length; i < len; i++ ) {
particle = this.particles[i];
// first argument, particle, is what this will be inside function
// second argument is the arguments for that function
particle[ methodName ].apply( particle, args );
}
};
// --------------------------...