import Rx, { Observable } from 'rxjs'; import Grid from './grid'; import Particle from './particle'; import Controls from './controls'; import Random from './random'; import { BEHAVIOR, CONTROLS, ENTITIES } from './enums'; function Animation(observables, id, behavior) { this.id = id; this.observables = observables; this.particles = []; this.grid = new Grid(); this.fpsInterval = null; this.behavior = behavior || BEHAVIOR.FREE; this.container = document.createElement('div'); this.container.className = 'animationContainer'; document.getElementById(id).appendChild(this.container); this.observables.count$.skip(1).subscribe(this.subscribeCount.bind(this)); this.observables.animating$.subscribe(this.subscribeAnimating.bind(this)); } Animation.prototype.subscribeAnimating = function(isAnimating) { if (isAnimating === false) { clearInterval(this.fpsInterval); } else { const { fps$ } = this.observables; this.fpsInterval = setInterval(fps$.next.bind(fps$), 1000 / 32); } } Animation.prototype.subscribeCount = function(count) { const bounds = this.container.getBoundingClientRect(); while (this.particles.length > count) { const p = this.particles.pop(); p.remove(); } while (this.particles.length < count) { const p = new Particle(this.container, bounds, this.grid, this.observables, this.behavior); this.particles.push(p); } } Animation.prototype.addHazards = function() { const bounds = this.container.getBoundingClientRect(); 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); this.grid.setArea({ x: Random.num(0, bounds.width - w), y: Random.num(0, bounds.height - h), w, h, type: ENTITIES.HAZARD }, this.container); } } export default Animation;