import Rx, { Observable } from 'rxjs'; import Particle from './particle'; import Grid from './grid'; import Controls from './controls'; import Random from './random'; import { CONTROLS, ENTITIES } from './enums'; function Animation2b() { this.options = { count: 1, maxCount: 1000, speed: 4 }; this.container = document.getElementById('animation2b'); this.particles = []; this.grid = this.createGlobalGrid(this.container, this.bounds); const controls = new Controls( document.getElementById('controls2b'), this.options ); controls.mount().subscribe(this.subscriber.bind(this)); this.updateAnimating(this.options.animating); this.updateCount(this.options.count); }; Animation2b.prototype.subscriber = function({ key, value }) { switch(key) { case CONTROLS.ANIMATING: this.updateAnimating(value); break; case CONTROLS.COUNT: this.updateCount(value); break; case CONTROLS.SPEED: this.updateSpeed(value); break; } } Animation2b.prototype.nextFrame = function() { this.particles.forEach(p => p.nextFrame()); } Animation2b.prototype.updateAnimating = function(isAnimating) { this.options.animating = isAnimating; if (isAnimating) { const fps$ = Rx.Observable.interval(1000 / 32) .takeWhile(_ => this.options.animating); fps$.subscribe(this.nextFrame.bind(this)); } } Animation2b.prototype.updateCount = function(count) { const bounds = this.container.getBoundingClientRect(); while (this.particles.length > count) { delete this.particles.pop().remove(); } while (this.particles.length < count) { const p = new Particle(this.container, bounds, this.options, this.grid); this.particles.push(p); } } Animation2b.prototype.updateSpeed = function(value) { this.options.speed = value; this.particles.forEach(p => p.updateConfig({ speed: value })); } Animation2b.prototype.createGlobalGrid = function() { const bounds = this.container.getBoundingClientRect(); const grid = new Grid(); const n = Random.num(1, 3); for (let i = 0; i < n; i++) { const w = Random.num(50, 200); const h = Random.num(50, 200); grid.setArea({ x: Random.num(0, bounds.width - w), y: Random.num(0, bounds.height - h), w, h, type: ENTITIES.HAZARD }, this.container); } return grid; } export default Animation2b;