UNPKG

@tsparticles/engine

Version:

Easily create highly customizable particle, confetti and fireworks animations and use them as animated backgrounds for your website. Ready to use components available also for React, Vue.js (2.x and 3.x), Angular, Svelte, jQuery, Preact, Riot.js, Inferno.

474 lines (473 loc) • 16.6 kB
import { animate, cancelAnimation, getRangeValue } from "../Utils/MathUtils.js"; import { defaultFps, defaultFpsLimit, millisecondsToSeconds, minFpsLimit } from "./Utils/Constants.js"; import { getItemMapFromInitializer, getItemsFromInitializer } from "../Utils/Utils.js"; import { CanvasManager } from "./CanvasManager.js"; import { EventListeners } from "./Utils/EventListeners.js"; import { EventType } from "../Enums/Types/EventType.js"; import { HdrMode } from "../Enums/Modes/HdrMode.js"; import { Options } from "../Options/Classes/Options.js"; import { ParticlesManager } from "./ParticlesManager.js"; import { Retina } from "./Retina.js"; import { getLogger } from "../Utils/LogUtils.js"; import { loadOptions } from "../Utils/OptionLoader.js"; import { toEnumValue } from "../Utils/TypeUtils.js"; function guardCheck(container) { return !container.destroyed; } function updateDelta(delta, value, fpsLimit = defaultFps, smooth = false) { delta.value = value; delta.factor = smooth ? defaultFps / fpsLimit : (defaultFps * value) / millisecondsToSeconds; } function loadContainerOptions(pluginManager, container, ...sourceOptionsArr) { const options = new Options(pluginManager, container); loadOptions(options, ...sourceOptionsArr); return options; } const emptyPlugins = Object.freeze([]); export class Container { actualOptions; canvas; destroyed; effectDrawers; fpsLimit; hdr; hdrMode; id; pageHidden; particles; particleUpdaters; peakNits; retina; shapeDrawers; started; zLayers; #delay; #delayResolve; #delayTimeout; #delta = { value: 0, factor: 0 }; #dispatchCallback; #drawAnimationFrame; #duration; #eventListeners; #firstStart; #initialSourceOptions; #lastFrameTime; #lifeTime; #onDestroy; #options; #particleCreatedPlugins = emptyPlugins; #particleDestroyedPlugins = emptyPlugins; #particlePositionPlugins = emptyPlugins; #paused; #pluginManager; #plugins = emptyPlugins; #smooth; #sourceOptions; #startCancel; #startGeneration = 0; #startPromise; constructor(params) { const { dispatchCallback, pluginManager, id, onDestroy, sourceOptions } = params; this.#pluginManager = pluginManager; this.#dispatchCallback = dispatchCallback; this.#onDestroy = onDestroy; this.id = Symbol(id); this.fpsLimit = 120; this.hdr = false; this.hdrMode = HdrMode.standard; this.peakNits = 400; this.#smooth = false; this.#delay = 0; this.#duration = 0; this.#lifeTime = 0; this.#firstStart = true; this.started = false; this.destroyed = false; this.#paused = true; this.#lastFrameTime = 0; this.zLayers = 100; this.pageHidden = false; this.#sourceOptions = sourceOptions; this.#initialSourceOptions = sourceOptions; this.effectDrawers = new Map(); this.shapeDrawers = new Map(); this.particleUpdaters = []; this.retina = new Retina(this); this.canvas = new CanvasManager(this.#pluginManager, this); this.particles = new ParticlesManager(this.#pluginManager, this); this.#options = loadContainerOptions(this.#pluginManager, this); this.actualOptions = loadContainerOptions(this.#pluginManager, this); this.#eventListeners = new EventListeners(this); this.dispatchEvent(EventType.containerBuilt); } get animationStatus() { return !this.#paused && !this.pageHidden && guardCheck(this); } get options() { return this.#options; } get particleCreatedPlugins() { return this.#particleCreatedPlugins; } get particleDestroyedPlugins() { return this.#particleDestroyedPlugins; } get particlePositionPlugins() { return this.#particlePositionPlugins; } get plugins() { return this.#plugins; } get sourceOptions() { return this.#sourceOptions; } addLifeTime(value) { this.#lifeTime += value; } alive() { return !this.#duration || this.#lifeTime <= this.#duration; } destroy(remove = true) { if (!guardCheck(this)) { return; } this.stop(); this.particles.destroy(); this.canvas.destroy(); for (const [, effectDrawer] of this.effectDrawers) { effectDrawer.destroy?.(this); } for (const [, shapeDrawer] of this.shapeDrawers) { shapeDrawer.destroy?.(this); } for (const plugin of this.plugins) { plugin.destroy?.(); } this.effectDrawers = new Map(); this.shapeDrawers = new Map(); this.particleUpdaters = []; this.#plugins = emptyPlugins; this.destroyed = true; this.#onDestroy(remove); this.dispatchEvent(EventType.containerDestroyed); } dispatchEvent(type, data) { this.#dispatchCallback(type, { container: this, data, }); } draw(force) { if (!guardCheck(this)) { return; } if (this.#drawAnimationFrame !== undefined) { if (!force) { return; } cancelAnimation(this.#drawAnimationFrame); this.#drawAnimationFrame = undefined; } let refreshTime = force; this.#drawAnimationFrame = animate((timestamp) => { this.#drawAnimationFrame = undefined; if (refreshTime) { this.#lastFrameTime = undefined; refreshTime = false; } this.#nextFrame(timestamp); }); } async export(type, options = {}) { for (const plugin of this.plugins) { if (!plugin.export) { continue; } const res = await plugin.export(type, options); if (!res.supported) { continue; } return res.blob; } getLogger().error(`Export plugin with type ${type} not found`); return undefined; } async init() { if (!guardCheck(this)) { return; } const generation = this.#startGeneration, allContainerPlugins = new Map(); for (const plugin of this.#pluginManager.plugins) { const containerPlugin = await plugin.getPlugin(this); if (generation !== this.#startGeneration || this.destroyed) { return; } if (containerPlugin.preInit) { await containerPlugin.preInit(); if (generation !== this.#startGeneration) { return; } } allContainerPlugins.set(plugin, containerPlugin); } await this.initDrawersAndUpdaters(); if (generation !== this.#startGeneration) { return; } this.#options = loadContainerOptions(this.#pluginManager, this, this.#initialSourceOptions, this.sourceOptions); this.actualOptions = loadContainerOptions(this.#pluginManager, this, this.#options); this.#initPlugins(allContainerPlugins); this.retina.init(); this.canvas.init(); this.updateActualOptions(); this.canvas.initBackground(); this.canvas.resize(); const { delay, duration, fpsLimit, smooth, zLayers } = this.actualOptions, hdrOptions = this.actualOptions.hdr; this.hdrMode = toEnumValue(HdrMode, hdrOptions.mode, HdrMode.standard); this.peakNits = hdrOptions.peakNits; this.zLayers = zLayers; this.#duration = getRangeValue(duration) * millisecondsToSeconds; this.#delay = getRangeValue(delay) * millisecondsToSeconds; this.#lifeTime = 0; this.fpsLimit = fpsLimit > minFpsLimit ? fpsLimit : defaultFpsLimit; this.#smooth = smooth; for (const plugin of this.plugins) { await plugin.init?.(); if (generation !== this.#startGeneration) { return; } } await this.particles.init(); if (generation !== this.#startGeneration) { return; } this.dispatchEvent(EventType.containerInit); this.particles.setDensity(); for (const plugin of this.plugins) { plugin.particlesSetup?.(); } this.dispatchEvent(EventType.particlesSetup); } async initDrawersAndUpdaters() { const pluginManager = this.#pluginManager; this.effectDrawers = await getItemMapFromInitializer(this, pluginManager.initializers.effects); this.shapeDrawers = await getItemMapFromInitializer(this, pluginManager.initializers.shapes); this.particleUpdaters = await getItemsFromInitializer(this, pluginManager.initializers.updaters); } pause() { if (!guardCheck(this)) { return; } if (this.#drawAnimationFrame !== undefined) { cancelAnimation(this.#drawAnimationFrame); this.#drawAnimationFrame = undefined; } if (this.#paused) { return; } for (const plugin of this.plugins) { plugin.pause?.(); } if (!this.pageHidden) { this.#paused = true; } this.dispatchEvent(EventType.containerPaused); } play(force) { if (!guardCheck(this)) { return; } const needsUpdate = this.#paused || force; if (this.#firstStart && !this.actualOptions.autoPlay) { this.#firstStart = false; return; } if (this.#paused) { this.#paused = false; } if (needsUpdate) { for (const plugin of this.plugins) { if (plugin.play) { plugin.play(); } } } this.dispatchEvent(EventType.containerPlay); this.draw(needsUpdate ?? false); } async refresh() { if (!guardCheck(this)) { return; } this.stop(); return this.start(); } async reset(sourceOptions) { if (!guardCheck(this)) { return; } this.#initialSourceOptions = sourceOptions; this.#sourceOptions = sourceOptions; this.#options = loadContainerOptions(this.#pluginManager, this, this.#initialSourceOptions, this.sourceOptions); this.actualOptions = loadContainerOptions(this.#pluginManager, this, this.#options); return this.refresh(); } async start() { if (!guardCheck(this) || this.started) { return; } if (this.#startPromise) { return this.#startPromise; } const generation = ++this.#startGeneration; let cancel; const cancelled = new Promise(resolve => { cancel = resolve; }); this.#startCancel = cancel; this.#startPromise = (async () => { try { await Promise.race([this.init(), cancelled]); if (generation !== this.#startGeneration) { return; } this.started = true; await Promise.race([ new Promise(resolve => { this.#delayResolve = resolve; this.#delayTimeout = setTimeout(() => { this.#delayTimeout = undefined; this.#delayResolve = undefined; resolve(); }, this.#delay); }), cancelled, ]); if (generation !== this.#startGeneration || this.destroyed) { return; } this.#eventListeners.addListeners(); const startPlugins = async () => { for (const plugin of this.plugins) { if (generation !== this.#startGeneration) { return; } await plugin.start?.(); } }; await Promise.race([startPlugins(), cancelled]); if (generation !== this.#startGeneration) { return; } this.dispatchEvent(EventType.containerStarted); this.play(); } catch (error) { if (generation === this.#startGeneration && !this.destroyed) { this.stop(); } throw error; } finally { if (generation === this.#startGeneration) { this.#startPromise = undefined; this.#startCancel = undefined; } } })(); return this.#startPromise; } stop() { if (!guardCheck(this)) { return; } this.#startGeneration++; this.#startCancel?.(); this.#startCancel = undefined; this.#startPromise = undefined; if (!this.started) { return; } if (this.#delayTimeout !== undefined) { clearTimeout(this.#delayTimeout); this.#delayTimeout = undefined; this.#delayResolve?.(); this.#delayResolve = undefined; } this.#firstStart = true; this.started = false; this.#eventListeners.removeListeners(); this.pause(); this.particles.clear(); this.canvas.stop(); for (const plugin of this.plugins) { plugin.stop?.(); } this.#particleCreatedPlugins = emptyPlugins; this.#particleDestroyedPlugins = emptyPlugins; this.#particlePositionPlugins = emptyPlugins; this.#sourceOptions = this.#options; this.dispatchEvent(EventType.containerStopped); } updateActualOptions() { let refresh = false; for (const plugin of this.plugins) { if (plugin.updateActualOptions) { refresh = plugin.updateActualOptions() || refresh; } } this.canvas.render.updateBackgroundElement(); return refresh; } #initPlugins(allContainerPlugins) { const plugins = [], particleCreatedPlugins = [], particleDestroyedPlugins = [], particlePositionPlugins = []; for (const [plugin, containerPlugin] of allContainerPlugins) { if (!plugin.needsPlugin(this.actualOptions)) { continue; } plugins.push(containerPlugin); if (containerPlugin.particleCreated) { particleCreatedPlugins.push(containerPlugin); } if (containerPlugin.particleDestroyed) { particleDestroyedPlugins.push(containerPlugin); } if (containerPlugin.particlePosition) { particlePositionPlugins.push(containerPlugin); } } this.#plugins = Object.freeze(plugins); this.#particleCreatedPlugins = Object.freeze(particleCreatedPlugins); this.#particleDestroyedPlugins = Object.freeze(particleDestroyedPlugins); this.#particlePositionPlugins = Object.freeze(particlePositionPlugins); } #nextFrame(timestamp) { try { if (!this.#smooth && this.#lastFrameTime !== undefined && timestamp < this.#lastFrameTime + millisecondsToSeconds / this.fpsLimit) { this.draw(false); return; } this.#lastFrameTime ??= timestamp; updateDelta(this.#delta, timestamp - this.#lastFrameTime, this.fpsLimit, this.#smooth); this.addLifeTime(this.#delta.value); this.#lastFrameTime = timestamp; if (this.#delta.value > millisecondsToSeconds) { this.draw(false); return; } this.canvas.render.drawParticles(this.#delta); if (!this.alive()) { this.destroy(); return; } if (this.animationStatus) { this.draw(false); } } catch (e) { getLogger().error("error in animation loop", e); } } }