diff --git a/.github/workflows/deploy-websites.yml b/.github/workflows/deploy-websites.yml index 5cf74051e0d..090e50ce4bf 100644 --- a/.github/workflows/deploy-websites.yml +++ b/.github/workflows/deploy-websites.yml @@ -22,6 +22,7 @@ permissions: env: NX_CLOUD_ACCESS_TOKEN: "${{ secrets.NX_CLOUD_ACCESS_TOKEN }}" + NODE_OPTIONS: "--max-old-space-size=4096" jobs: build-and-deploy: diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 1104573e0a4..91f22431065 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -14,6 +14,7 @@ env: NODE_VERSION: "24" NX_CLOUD_ACCESS_TOKEN: "${{ secrets.NX_CLOUD_ACCESS_TOKEN }}" firebaseToken: "${{ secrets.FIREBASE_SERVICE_ACCOUNT_TSPARTICLES }}" + NODE_OPTIONS: "--max-old-space-size=4096" jobs: build-and-deploy: diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index 49b802d80d7..a4a27d824c1 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -22,6 +22,7 @@ env: RELEASE_UPLOAD_RETRIES: 6 RELEASE_RETRY_BASE_DELAY: 10 IS_STABLE: ${{ !contains(github.ref, '-alpha.') && !contains(github.ref, '-beta.') }} + NODE_OPTIONS: "--max-old-space-size=4096" jobs: publish: @@ -51,8 +52,6 @@ jobs: - name: Build All Packages run: pnpm run build:ci - env: - CI: true # 📦 ZIP artifacts (solo stable) - name: Generate zip artifacts diff --git a/websites/confetti/vite.config.js b/websites/confetti/vite.config.js index 48bb91429e9..c3d98539f89 100644 --- a/websites/confetti/vite.config.js +++ b/websites/confetti/vite.config.js @@ -14,6 +14,6 @@ export default defineConfig({ ], build: { outDir: 'dist', - minify: true, + minify: false, }, }); diff --git a/websites/ribbons/vite.config.js b/websites/ribbons/vite.config.js index 69e8f6d09bf..3b39010f4f9 100644 --- a/websites/ribbons/vite.config.js +++ b/websites/ribbons/vite.config.js @@ -14,6 +14,6 @@ export default defineConfig({ ], build: { outDir: 'dist', - minify: true, + minify: false, }, }); diff --git a/websites/website/docs/de/guide/bundles-all.md b/websites/website/docs/de/guide/bundles-all.md index 2aa3c667b16..d72e69f8f22 100644 --- a/websites/website/docs/de/guide/bundles-all.md +++ b/websites/website/docs/de/guide/bundles-all.md @@ -1,21 +1,42 @@ # Bundle: All -`@tsparticles/all` laedt alle offiziellen Features und ist ideal fuer schnelles Prototyping. +`@tsparticles/all` lädt **alles** aus dem tsParticles-Repository: jede Form, Interaktion, Aktualisierer, Effekt, Pfad, Easing, Plugin und Export. Es ist das größte Bundle, gedacht für Prototyping und Demos. -## Wann All waehlen +## Enthaltene Funktionen -- Du willst sofort alle Features verfuegbar haben. -- Du testest Optionen schnell. -- Bundle-Groesse ist weniger wichtig als Setup-Geschwindigkeit. +Erbt alles von `tsparticles` (full) plus: + +**Alle Formen:** Pfeil, Karten, Zahnrad, Herz, Unendlichkeit, Matrix, Pfad, Ribbon, abgerundetes Polygon, abgerundetes Rechteck, Spirale, Squircle + +**Alle externen Interaktionen:** Kanone, Licht, Partikel, Pop, Partikel-Abstoßen + +**Alle Effekte:** Blase, Filter, Partikel, Schatten, Spur + +**Alle Pfadgeneratoren:** Äste, Brownsch, Curl-Noise, Kurven, Fraktal-Noise, Gitter, Levy, Perlin-Noise, Polygon, Zufall, Simplex-Noise, Spirale, SVG, Zickzack + +**Alle Easings:** Back, Bounce, Circ, Cubic, Elastic, Expo, Gaussian, Linear, Quad, Quart, Quint, Sigmoid, Sine, Smoothstep + +**Alle Farb-Plugins:** HEX, HSL, RGB, HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH + +**Alle Plugins:** Absorber, Hintergrundmaske, Canvas-Maske, Emitter (alle Formen), Easings (alle), Export-Bild, Export-JSON, Export-Video, Infektion, Manuelle Partikel, Bewegung, Poisson-Scheibe, Polygon-Maske, Responsive, Töne, Themes, Spur, Zoom + +**Alle Aktualisierer:** Zerstören, Farbverlauf, Lebenszyklus, Opazität, Orbit, Aus-Modi, Farbe, Rollen, Drehen, Größe, Neigen, Funkeln, Wackeln + +## Wann verwenden + +- Schnelles Prototyping, um Möglichkeiten zu erkunden +- Demos und Vorführungen +- Entwicklungsumgebungen, in denen die Größe keine Rolle spielt +- **Nicht für die Produktion empfohlen** — bevorzuge gezieltere Bundles ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/all ``` -## Setup-Beispiel - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadAll } from "@tsparticles/all"; @@ -25,20 +46,48 @@ await loadAll(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { number: { value: 100 }, + shape: { type: "heart" }, move: { enable: true, speed: 2 }, }, }, }); ``` -## Haeufige Stolperfallen +### CDN (Script-Tags) + +```html + + + +``` + +## Unterschied zwischen `tsparticles` und `@tsparticles/all` + +Siehe die Vergleichstabelle auf der [Bundles-Full-Seite](/de/guide/bundles-full) für die detaillierte Aufschlüsselung. + +## Häufige Fehler -- In Produktion nutzen, obwohl ein kleineres Bundle besser waere. -- `tsParticles.load(...)` vor `loadAll(...)` aufrufen. +- Verwendung in der Produktion — bevorzuge `@tsparticles/slim` oder `tsparticles` für kleinere Bundles. +- `tsParticles.load()` vor `loadAll(tsParticles)` aufrufen. -## Verwandte Seiten +## Siehe auch -- Ueberblick: [`/guide/bundles`](/de/guide/bundles) -- Installationsmatrix: [`/guide/installation`](/de/guide/installation) +- [Bundle-Übersicht](/de/guide/bundles) +- [Installationsanleitung](/de/guide/installation) diff --git a/websites/website/docs/de/guide/bundles-basic.md b/websites/website/docs/de/guide/bundles-basic.md index f818e59bd66..9ab2b59e3cc 100644 --- a/websites/website/docs/de/guide/bundles-basic.md +++ b/websites/website/docs/de/guide/bundles-basic.md @@ -1,21 +1,46 @@ # Bundle: Basic -`@tsparticles/basic` ist fuer extra-leichte Setups mit minimaler Laufzeit gedacht. +`@tsparticles/basic` ist das leichteste Bundle. Enthält nur das Nötigste: Kreise, die sich mit animierbarer Opazität und Größe bewegen. -## Wann Basic waehlen +## Enthaltene Funktionen -- Bundle-Groesse hat oberste Prioritaet. -- Du brauchst nur grundlegende Effekte. -- Erweiterte Plugins sind nicht erforderlich. +**Formen:** Kreis + +**Aktualisierer:** + +- Farbe +- Opazität +- Aus-Modi (Verhalten beim Verlassen des Bildschirms) +- Größe + +**Plugins:** + +- Bewegung +- Mischung (Farbmischung) +- HEX-, HSL-, RGB-Farb-Plugins + +**Nicht enthalten:** + +- Maus-/Touch-Interaktionen +- Partikelverbindungen +- Andere Formen (Quadrate, Sterne, Bilder, Polygone etc.) +- Emitter, Absorber, Töne +- Drehung, Lebenszyklus, Rollen, Neigen, Wackeln + +## Wann verwenden + +- Die Bundle-Größe hat oberste Priorität +- Du brauchst nur sich bewegende Punkte +- Keine Interaktionen oder komplexen Formen nötig ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/basic ``` -## Setup-Beispiel - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadBasic } from "@tsparticles/basic"; @@ -25,20 +50,48 @@ await loadBasic(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#ffffff" }, particles: { number: { value: 50 }, - move: { enable: true, speed: 1.5 }, + color: { value: ["#5bc0eb", "#fde74c", "#9bc53d"] }, + size: { + value: { min: 300, max: 400 }, + animation: { enable: true, speed: 100 }, + }, + move: { enable: true, speed: 10 }, }, }, }); ``` -## Haeufige Stolperfallen +### CDN (Script-Tags) + +```html + + + +``` + +## Häufige Fehler -- Features erwarten, die nur in nicht enthaltenen Plugins stecken. -- `tsParticles.load(...)` vor `loadBasic(...)` aufrufen. +- Funktionen erwarten, die nicht enthalten sind (z.B. `links`, Maus-Interaktionen) — diese erfordern umfangreichere Bundles. +- `tsParticles.load()` vor `loadBasic(tsParticles)` aufrufen — Formen und Aktualisierer sind noch nicht registriert. +- Nur `@tsparticles/engine` ohne ein Bundle installieren — die Engine allein zeichnet nichts. -## Verwandte Seiten +## Siehe auch -- Ueberblick: [`/guide/bundles`](/de/guide/bundles) -- Installationsmatrix: [`/guide/installation`](/de/guide/installation) +- [Bundle-Übersicht](/de/guide/bundles) +- [Installationsanleitung](/de/guide/installation) diff --git a/websites/website/docs/de/guide/bundles-confetti.md b/websites/website/docs/de/guide/bundles-confetti.md index abdb8d7ca99..407f42e3bea 100644 --- a/websites/website/docs/de/guide/bundles-confetti.md +++ b/websites/website/docs/de/guide/bundles-confetti.md @@ -1,42 +1,83 @@ # Bundle: Confetti -`@tsparticles/confetti` bietet eine fokussierte API fuer Konfetti-Effekte mit minimalem Setup. +`@tsparticles/confetti` bietet eine vereinfachte API zum Erstellen von Konfetti-Effekten mit einem einzigen Funktionsaufruf. Keine direkte Interaktion mit `tsParticles` nötig. -## Wann Confetti waehlen +## Enthaltene Funktionen -- Du willst Feier-Effekte mit einem Aufruf. -- Du willst die Engine nicht manuell verdrahten. -- Du bevorzugst eine kompakte API fuer UI-Events. +**Formen:** Kreis, Herz, Karten (französische Farben: Herz, Karo, Kreuz, Pik), Emoji, Bilder, Polygon, Quadrat, Stern + +**Interne Plugins:** Emitter, Bewegung (respektiert die Benutzereinstellung zur reduzierten Bewegung) + +**Aktualisierer:** Lebenszyklus, Rollen, Drehen, Neigen, Wackeln + +**API:** `confetti(options)` oder `confetti(canvasId, options)` + +## Wann verwenden + +- "Glückwunsch!"- oder "Alles Gute zum Geburtstag!"-Button +- Schneller Feiereffekt +- Du möchtest die Engine nicht manuell konfigurieren ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/confetti ``` -## Setup-Beispiel - ```ts import { confetti } from "@tsparticles/confetti"; +// Basiseffekt await confetti({ - count: 80, - spread: 60, + particleCount: 100, + spread: 70, + origin: { x: 0.5, y: 0.5 }, }); -await confetti("canvas-id", { - count: 50, +// Auf einer bestimmten Canvas +await confetti("my-canvas-id", { + particleCount: 50, angle: 90, spread: 45, + colors: ["#ff0000", "#00ff00", "#0000ff"], }); ``` -## Haeufige Stolperfallen +### CDN (Script-Tag) + +```html + + +``` + +### Hauptparameter + +| Parameter | Typ | Standard | Beschreibung | +| --------------- | -------- | ------------ | ---------------------------------------------------- | +| `particleCount` | number | 50 | Anzahl der Konfettiteilchen | +| `spread` | number | 60 | Streuwinkel (Grad) | +| `angle` | number | 90 | Richtung (Grad, 90 = nach unten) | +| `startVelocity` | number | 30 | Anfangsgeschwindigkeit | +| `colors` | string[] | — | Konfettifarben | +| `origin` | { x, y } | { 0.5, 0.5 } | Ursprungspunkt (0-1) | +| `drift` | number | 0 | Horizontale Drift | +| `shapes` | string[] | — | Formen: "circle", "heart", "square", "star", "cards" | + +## Häufige Fehler -- Annehmen, dass `tsParticles` aus `@tsparticles/confetti` exportiert wird. +- Denken, dass `tsParticles` von `@tsparticles/confetti` exportiert wird — das ist nicht der Fall. - Dieselbe Canvas-ID unbeabsichtigt wiederverwenden. +- `confetti` in einer Schleife aufrufen, ohne die Leistung zu verwalten — verwende ein angemessenes Intervall oder stoppe die Animation, wenn sie fertig ist. -## Verwandte Seiten +## Siehe auch -- Ueberblick: [`/guide/bundles`](/de/guide/bundles) -- Bundle-Playground: [`/playground/bundles`](/de/playground/bundles) +- [Bundle-Übersicht](/de/guide/bundles) +- [Feuerwerk-Bundle](/de/guide/bundles-fireworks) diff --git a/websites/website/docs/de/guide/bundles-fireworks.md b/websites/website/docs/de/guide/bundles-fireworks.md index b01ee5ef428..f367c1d6413 100644 --- a/websites/website/docs/de/guide/bundles-fireworks.md +++ b/websites/website/docs/de/guide/bundles-fireworks.md @@ -1,44 +1,81 @@ # Bundle: Fireworks -`@tsparticles/fireworks` bietet eine fokussierte API fuer Feuerwerk-Effekte mit minimalem Setup. +`@tsparticles/fireworks` bietet eine vereinfachte API zum Erstellen von Feuerwerkseffekten mit einem einzigen Funktionsaufruf. Unterstützt Töne, benutzerdefinierte Farben und Instanzsteuerung (Pause/Play). -## Wann Fireworks waehlen +## Enthaltene Funktionen -- Du willst Fireworks-Animationen mit einem Aufruf. -- Du brauchst kein direktes Engine-Wiring. -- Du bevorzugst eine kompakte API fuer Feier-Momente. +**Formen:** Linie, Kreis (von basic) + +**Interne Plugins:** Emitter, Emitter-Form-Quadrat, Mischung (Farbmischung), Töne + +**Aktualisierer:** Zerstören, Lebenszyklus, Farbe, Drehen + +**API:** `fireworks(options)` — gibt eine steuerbare Instanz zurück + +## Wann verwenden + +- Neujahrs- oder Feier-Effekt +- Feier-UI +- Du möchtest die Engine nicht manuell konfigurieren ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/fireworks ``` -## Setup-Beispiel - ```ts import { fireworks } from "@tsparticles/fireworks"; +// Basiseffekt const instance = await fireworks({ - colors: ["#ffffff", "#ff0000"], - sounds: false, + colors: ["#ffffff", "#ff0000", "#00ff00", "#0000ff"], + sounds: true, }); +// Instanzsteuerung instance?.pause(); instance?.play(); -await fireworks("canvas-id", { +// Auf einer bestimmten Canvas +await fireworks("my-canvas", { rate: 3, speed: { min: 10, max: 25 }, + sounds: false, }); ``` -## Haeufige Stolperfallen +### CDN (Script-Tag) + +```html + + +``` + +### Hauptparameter + +| Parameter | Typ | Standard | Beschreibung | +| ------------ | ------------ | -------- | ------------------------- | +| `colors` | string[] | — | Explosionsfarben | +| `rate` | number | — | Feuerwerke pro Sekunde | +| `speed` | { min, max } | — | Partikelgeschwindigkeit | +| `sounds` | boolean | true | Soundeffekte aktivieren | +| `gravity` | number | — | Schwerkraft (Standard: 0) | +| `opacity` | number | — | Opazität (0-1) | +| `brightness` | { min, max } | — | Explosionshelligkeit | + +## Häufige Fehler -- Annehmen, dass `tsParticles` aus `@tsparticles/fireworks` exportiert wird. -- `fireworks(...)` wiederholt aufrufen, ohne die Instanz zu verwalten. +- Denken, dass `tsParticles` von `@tsparticles/fireworks` exportiert wird — das ist nicht der Fall. +- `fireworks()` in einer Schleife aufrufen, ohne die Instanz zu verwalten — der Effekt ist bereits kontinuierlich. +- Die Instanz nicht stoppen, wenn die Seite verlassen wird — rufe `instance?.pause()` oder `instance?.stop()` auf. -## Verwandte Seiten +## Siehe auch -- Ueberblick: [`/guide/bundles`](/de/guide/bundles) -- Bundle-Playground: [`/playground/bundles`](/de/playground/bundles) +- [Bundle-Übersicht](/de/guide/bundles) +- [Konfetti-Bundle](/de/guide/bundles-confetti) diff --git a/websites/website/docs/de/guide/bundles-full.md b/websites/website/docs/de/guide/bundles-full.md index 322853ed2a8..71a702a5ff0 100644 --- a/websites/website/docs/de/guide/bundles-full.md +++ b/websites/website/docs/de/guide/bundles-full.md @@ -1,21 +1,48 @@ # Bundle: tsparticles (Full) -`tsparticles` ist das Full-Bundle und enthaelt einen breiten Satz offizieller Features mit nur einem Loader. +`tsparticles` (npm: `tsparticles`, Loader: `loadFull`) ist das offizielle Full-Bundle. Enthält alles von Slim plus Emitter, Absorber, Textformen und erweiterte Animationen (Wobble, Roll, Tilt, Twinkle, Destroy). -## Wann tsparticles (Full) waehlen +## Enthaltene Funktionen -- Du brauchst viele offizielle Features ohne manuelle Plugin-Auswahl. -- Du willst eine komplette, produktionsreife Basis vor dem Feintuning. -- Du bevorzugst Engine-Kontrolle ueber die `tsParticles`-API. +Erbt alles von `@tsparticles/slim` plus: + +**Zusätzliche Formen:** Text (mit benutzerdefinierten Schriftarten) + +**Zusätzliche externe Interaktionen:** + +- Ziehen (Partikel mit der Maus ziehen) +- Spur (Partikelspur hinter der Maus) + +**Zusätzliche Aktualisierer:** + +- Zerstören (Partikelzerstörungs-Animation) +- Rollen +- Neigen (3D-Neigung) +- Funkeln (intermittierendes Glitzern) +- Wackeln (Oszillation) + +**Plugins:** + +- Absorber (schwarze Löcher, die Partikel einsaugen) +- Emitter (kontinuierliche Partikelquellen) +- Emitter-Form-Kreis, Emitter-Form-Quadrat (Emitterformen) + +## Wann verwenden + +- Du brauchst Emitter (Partikel, die kontinuierlich erzeugt werden) +- Du brauchst Absorber (Partikel werden eingesaugt) +- Du brauchst Textformen mit benutzerdefinierten Schriftarten +- Du brauchst erweiterte Animationen (Wobble, Tilt, Roll, Twinkle) +- Gute Zwischenstufe vor dem Wechsel zu einzelnen Plugins ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine tsparticles ``` -## Setup-Beispiel - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadFull } from "tsparticles"; @@ -25,20 +52,65 @@ await loadFull(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { - number: { value: 100 }, - move: { enable: true, speed: 2 }, + number: { value: 50 }, + shape: { type: "text", options: { text: ["🔥", "✨", "⭐"] } }, + size: { value: 24 }, + move: { enable: true, speed: 1 }, + wobble: { enable: true, distance: 10 }, + }, + emitters: { + direction: "top", + rate: { quantity: 2, delay: 0.3 }, }, }, }); ``` -## Haeufige Stolperfallen +### CDN (Script-Tags) + +```html + + + +``` + +## Unterschied zwischen `tsparticles` und `@tsparticles/all` + +| Aspekt | `tsparticles` (full) | `@tsparticles/all` | +| ------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| Größe | Mittel | Sehr groß | +| Formen | Kreis, Quadrat, Stern, Polygon, Linie, Bild, Emoji, Text | Alle Formen (Herz, Karten, Pfeil, Spirale, Zahnrad, abgerundetes Rechteck etc.) | +| Interaktionen | Slim + Ziehen + Spur | Alle (Kanone, Licht, Pop, Partikel, Abstoßen) | +| Pfade | Nur Quad-Easing | 14 Pfadgeneratoren | +| Effekte | Keine | 5 Effekte (Blase, Filter, Schatten etc.) | +| Exporte | Keine | Bild, JSON, Video | +| Zusätzliche Plugins | Absorber, Emitter | Alle (Töne, Themes, Spur, Zoom, Polygon-Maske, Canvas-Maske, Hintergrundmaske etc.) | +| Easing | Quad | 15 Easings | + +## Häufige Fehler -- `tsParticles.load(...)` vor `loadFull(...)` aufrufen. -- Annehmen, dass es dasselbe Paket wie `@tsparticles/all` ist (es sind verschiedene Bundles). +- `tsparticles` mit `@tsparticles/all` verwechseln — es sind unterschiedliche Pakete. +- `tsParticles.load()` vor `loadFull(tsParticles)` aufrufen. +- Das npm-Paket heißt `tsparticles` (nicht `@tsparticles/full`), der Loader heißt `loadFull`. -## Verwandte Seiten +## Siehe auch -- Ueberblick: [`/guide/bundles`](/de/guide/bundles) -- Installationsmatrix: [`/guide/installation`](/de/guide/installation) +- [Bundle-Übersicht](/de/guide/bundles) +- [Installationsanleitung](/de/guide/installation) diff --git a/websites/website/docs/de/guide/bundles-particles.md b/websites/website/docs/de/guide/bundles-particles.md index aef9f57eec1..04a47cd515c 100644 --- a/websites/website/docs/de/guide/bundles-particles.md +++ b/websites/website/docs/de/guide/bundles-particles.md @@ -1,42 +1,98 @@ # Bundle: Particles -`@tsparticles/particles` bietet eine fokussierte API fuer einfache Partikel-Hintergruende. +`@tsparticles/particles` bietet eine vereinfachte API zum Erstellen interaktiver Partikelhintergründe. Eine umfangreichere Alternative zu `@tsparticles/basic` mit einer dedizierten API anstelle der manuellen Engine-Konfiguration. -## Wann Particles waehlen +## Enthaltene Funktionen -- Du willst eine schnelle API fuer Partikel-Hintergruende. -- Du willst Engine/Plugins nicht manuell verdrahten. -- Du bevorzugst eine kompakte, app-aehnliche API. +**Formen:** Kreis (von basic) + +**Interne Plugins:** Interaktivität (Verbindungen, Kollisionen) + +**Interaktionen:** Verbindungen (Partikel-Links), Kollisionen + +**API:** `particles(options)` oder `particles(canvasId, options)` + +## Wann verwenden + +- Partikelhintergrund für eine Website +- Hintergrund mit Partikelverbindungen (Knoten-Netz-Effekt) +- Du möchtest die Engine nicht manuell konfigurieren ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/particles ``` -## Setup-Beispiel - ```ts import { particles } from "@tsparticles/particles"; +// Hintergrund mit Verbindungen await particles({ count: 120, links: true, - linksColor: "#0ff", + color: "#ffffff", + linksColor: "#00d8ff", + radius: 3, + speed: 2, + opacity: 0.8, }); -await particles("canvas-id", { +// Auf einer bestimmten Canvas +await particles("my-canvas", { count: 80, shape: ["circle", "square"], + links: true, }); + +// Mit benutzerdefinierten Farben +await particles({ + count: 100, + color: ["#ff6b6b", "#4ecdc4", "#45b7d1"], + links: false, +}); +``` + +### CDN (Script-Tag) + +```html + + ``` -## Haeufige Stolperfallen +### Hauptparameter + +| Parameter | Typ | Standard | Beschreibung | +| ------------ | ------------------ | ---------- | ------------------------ | +| `count` | number | 50 | Anzahl der Partikel | +| `radius` | number | 3 | Partikelradius | +| `speed` | number | 2 | Bewegungsgeschwindigkeit | +| `opacity` | number | 0.8 | Opazität (0-1) | +| `color` | string \| string[] | "#ffffff" | Partikelfarbe(n) | +| `links` | boolean | false | Verbindungen anzeigen | +| `linksColor` | string | "#ffffff" | Verbindungsfarbe | +| `linksWidth` | number | 1 | Verbindungsstärke | +| `shape` | string[] | ["circle"] | Partikelformen | + +## Häufige Fehler -- Annehmen, dass `tsParticles` aus `@tsparticles/particles` exportiert wird. +- Denken, dass `tsParticles` von `@tsparticles/particles` exportiert wird — das ist nicht der Fall. - Dieselbe Canvas-ID unbeabsichtigt wiederverwenden. +- Erweiterte Formen erwarten (Sterne, Polygone) — das Particles-Bundle basiert auf basic und verwendet nur Kreise. -## Verwandte Seiten +## Siehe auch -- Ueberblick: [`/guide/bundles`](/de/guide/bundles) -- Bundle-Playground: [`/playground/bundles`](/de/playground/bundles) +- [Bundle-Übersicht](/de/guide/bundles) +- [Erste Schritte](/de/guide/getting-started) diff --git a/websites/website/docs/de/guide/bundles-slim.md b/websites/website/docs/de/guide/bundles-slim.md index 67b294708d6..6836274b535 100644 --- a/websites/website/docs/de/guide/bundles-slim.md +++ b/websites/website/docs/de/guide/bundles-slim.md @@ -1,21 +1,61 @@ # Bundle: Slim -`@tsparticles/slim` ist die empfohlene Standardwahl fuer die meisten Projekte. +`@tsparticles/slim` ist das empfohlene Bundle für die meisten Projekte. Enthält alles, was für moderne Partikelanimationen mit Maus-Interaktionen, mehreren Formen und Partikelverbindungen benötigt wird. -## Wann Slim waehlen +## Enthaltene Funktionen -- Du willst ein gutes Gleichgewicht aus Groesse und Funktionen. -- Du nutzt die `tsParticles`-Engine-API direkt. -- Du brauchst gaengige Formen/Interaktionen ohne alles zu laden. +Erbt alles von `@tsparticles/basic` plus: + +**Formen:** Kreis, Quadrat, Stern, Polygon, Linie, Bild, Emoji + +**Externe Interaktionen (Maus/Touch):** + +- Anziehen +- Abprallen +- Blase +- Verbinden +- Zerstören +- Greifen +- Parallaxe +- Pausieren +- Schieben +- Entfernen +- Abstoßen +- Verlangsamen + +**Partikel-Interaktionen:** + +- Anziehen +- Kollisionen +- Verbindungen (Partikel-Links) + +**Zusätzliche Aktualisierer:** + +- Lebenszyklus +- Drehen + +**Plugins:** + +- Interaktivität +- Easing-Quad +- HEX-, HSL-, RGB-Farb-Plugins + +## Wann verwenden + +- Empfohlener Ausgangspunkt für die meisten Projekte +- Du brauchst mehrere Formen (Kreise, Sterne, Polygone, Bilder) +- Du brauchst Maus-Interaktionen (Klick, Hover, Blase, Abstoßen) +- Du brauchst Partikelverbindungen +- Gute Balance zwischen Bundle-Größe und Funktionen ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/slim ``` -## Setup-Beispiel - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; @@ -25,21 +65,47 @@ await loadSlim(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#0b1020" }, particles: { number: { value: 80 }, + links: { enable: true, distance: 150 }, move: { enable: true, speed: 2 }, - links: { enable: true }, + shape: { type: ["circle", "star", "square"] }, }, }, }); ``` -## Haeufige Stolperfallen +### CDN (Script-Tags) + +```html + + + +``` + +## Häufige Fehler -- `tsParticles.load(...)` vor `loadSlim(...)` aufrufen. -- Unterschiedliche Versionen von Engine und Plugins mischen. +- `tsParticles.load()` vor `loadSlim(tsParticles)` aufrufen. +- Unterschiedliche Versionen von Engine und Bundle mischen — halte sie auf dem gleichen Stand. +- Funktionen aus höheren Bundles erwarten (Emitter, Absorber, Text, Wobble) — dafür wird `tsparticles` (full) oder einzelne Plugins benötigt. -## Verwandte Seiten +## Siehe auch -- Ueberblick: [`/guide/bundles`](/de/guide/bundles) -- Installationsmatrix: [`/guide/installation`](/de/guide/installation) +- [Bundle-Übersicht](/de/guide/bundles) +- [Installationsanleitung](/de/guide/installation) diff --git a/websites/website/docs/de/guide/bundles.md b/websites/website/docs/de/guide/bundles.md index 04c1f219840..6b21af8ec36 100644 --- a/websites/website/docs/de/guide/bundles.md +++ b/websites/website/docs/de/guide/bundles.md @@ -1,104 +1,184 @@ # Bundle-Anleitung -Diese Seite hilft dir, das passende `tsParticles`-Bundle auszuwaehlen und schnell einzurichten. - -## Paketvergleich - -| Paket | Ideal fuer | Setup-Stil | -| ------------------------ | ------------------------------------------------------------ | ---------------------------------------------- | -| `@tsparticles/basic` | Sehr leichte Setups | `tsParticles` + `await loadBasic(tsParticles)` | -| `@tsparticles/slim` | Die meisten Websites/Apps | `tsParticles` + `await loadSlim(tsParticles)` | -| `tsparticles` | Vollstaendiger offizieller Feature-Satz mit Engine-Kontrolle | `tsParticles` + `await loadFull(tsParticles)` | -| `@tsparticles/all` | Alle Features, schnelles Prototyping | `tsParticles` + `await loadAll(tsParticles)` | -| `@tsparticles/confetti` | Konfetti-Effekte mit einem Aufruf | `await confetti(options)` | -| `@tsparticles/fireworks` | Feuerwerk-Effekte mit einem Aufruf | `await fireworks(options)` | -| `@tsparticles/particles` | Einfache API fuer Partikel-Hintergruende | `await particles(options)` | -| `@tsparticles/ribbons` | Ribbons-Effekte mit einem Aufruf | `await ribbons(options)` | - -## Bundle-Anleitungen - -- Basic: [`/guide/bundles-basic`](/de/guide/bundles-basic) -- Slim: [`/guide/bundles-slim`](/de/guide/bundles-slim) -- tsparticles (Full): [`/guide/bundles-full`](/de/guide/bundles-full) -- All: [`/guide/bundles-all`](/de/guide/bundles-all) -- Confetti: [`/guide/bundles-confetti`](/de/guide/bundles-confetti) -- Fireworks: [`/guide/bundles-fireworks`](/de/guide/bundles-fireworks) -- Particles: [`/guide/bundles-particles`](/de/guide/bundles-particles) -- Ribbons (Demo + Doku): [`/demos/recipes/ribbons`](/de/demos/recipes/ribbons) · - -## Installation - -Installiere den Paketpfad, der zu deinem Anwendungsfall passt. - -```bash -pnpm add @tsparticles/engine @tsparticles/basic -pnpm add @tsparticles/engine @tsparticles/slim -pnpm add @tsparticles/engine tsparticles -pnpm add @tsparticles/engine @tsparticles/all -pnpm add @tsparticles/confetti -pnpm add @tsparticles/fireworks -pnpm add @tsparticles/particles -pnpm add @tsparticles/ribbons +tsParticles ist modular. Das Paket `@tsparticles/engine` enthält nur die Kern-Engine; um sichtbare Effekte zu erzielen, musst du **Formen** (was gezeichnet wird), **Aktualisierer** (wie animiert wird), **Interaktionen** (Reaktion auf Maus/Touch) und **Plugins** (zusätzliche Funktionen) registrieren. All dies geschieht über **Bundles**. + +## Bundle-Kategorien + +| Kategorie | Bundle | API | +| --------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------- | +| Engine + Loader | `@tsparticles/basic`, `@tsparticles/slim`, `tsparticles`, `@tsparticles/all` | `tsParticles.load({ id, options })` | +| Dedizierte API | `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles`, `@tsparticles/ribbons` | `confetti({...})`, `fireworks({...})`, etc. | + +## Vollständiger Funktionsvergleich + +Legende: ● = enthalten, ○ = nicht enthalten + +| Funktion | basic | slim | full (`tsparticles`) | all | +| --------------------------------------------------------------------------------------------------- | ----- | ---- | -------------------- | ------------------ | +| **Formen** | | | | | +| Kreis | ● | ● | ● | ● | +| Quadrat | ○ | ● | ● | ● | +| Stern | ○ | ● | ● | ● | +| Polygon | ○ | ● | ● | ● | +| Linie | ○ | ● | ● | ● | +| Bild | ○ | ● | ● | ● | +| Emoji | ○ | ● | ● | ● | +| Text | ○ | ○ | ● | ● | +| Karten (Farben) | ○ | ○ | ○ | ● | +| Herz | ○ | ○ | ○ | ● | +| Pfeil | ○ | ○ | ○ | ● | +| Abgerundetes Rechteck | ○ | ○ | ○ | ● | +| Abgerundetes Polygon | ○ | ○ | ○ | ● | +| Spirale | ○ | ○ | ○ | ● | +| Squircle | ○ | ○ | ○ | ● | +| Zahnrad | ○ | ○ | ○ | ● | +| Unendlichkeit | ○ | ○ | ○ | ● | +| Matrix | ○ | ○ | ○ | ● | +| Pfad | ○ | ○ | ○ | ● | +| Ribbon | ○ | ○ | ○ | ● | +| **Externe Interaktionen (Maus/Touch)** | | | | | +| Anziehen | ○ | ● | ● | ● | +| Abprallen | ○ | ● | ● | ● | +| Blase | ○ | ● | ● | ● | +| Verbinden | ○ | ● | ● | ● | +| Zerstören | ○ | ● | ● | ● | +| Greifen | ○ | ● | ● | ● | +| Parallaxe | ○ | ● | ● | ● | +| Pausieren | ○ | ● | ● | ● | +| Schieben | ○ | ● | ● | ● | +| Entfernen | ○ | ● | ● | ● | +| Abstoßen | ○ | ● | ● | ● | +| Verlangsamen | ○ | ● | ● | ● | +| Ziehen | ○ | ○ | ● | ● | +| Spur | ○ | ○ | ● | ● | +| Kanone | ○ | ○ | ○ | ● | +| Partikel | ○ | ○ | ○ | ● | +| Pop | ○ | ○ | ○ | ● | +| Licht | ○ | ○ | ○ | ● | +| **Partikel-Interaktionen** | | | | | +| Verbindungen | ○ | ● | ● | ● | +| Kollisionen | ○ | ● | ● | ● | +| Anziehen | ○ | ● | ● | ● | +| Abstoßen | ○ | ○ | ○ | ● | +| **Aktualisierer (Animationen)** | | | | | +| Opazität | ● | ● | ● | ● | +| Größe | ● | ● | ● | ● | +| Aus-Modi | ● | ● | ● | ● | +| Farbe | ● | ● | ● | ● | +| Drehen | ○ | ● | ● | ● | +| Lebenszyklus | ○ | ● | ● | ● | +| Zerstören | ○ | ○ | ● | ● | +| Rollen | ○ | ○ | ● | ● | +| Neigen | ○ | ○ | ● | ● | +| Funkeln | ○ | ○ | ● | ● | +| Wackeln | ○ | ○ | ● | ● | +| Farbverlauf | ○ | ○ | ○ | ● | +| Orbit | ○ | ○ | ○ | ● | +| **Plugins** | | | | | +| Bewegung | ● | ● | ● | ● | +| Mischung | ● | ● | ● | ● | +| Emitter | ○ | ○ | ● | ● | +| Absorber | ○ | ○ | ● | ● | +| Töne | ○ | ○ | ○ | ● | +| Bewegung (Benutzereinst.) | ○ | ○ | ○ | ● | +| Themes | ○ | ○ | ○ | ● | +| Polygon-Maske | ○ | ○ | ○ | ● | +| Canvas-Maske | ○ | ○ | ○ | ● | +| Hintergrundmaske | ○ | ○ | ○ | ● | +| Export (Bild, JSON, Video) | ○ | ○ | ○ | ● | +| Manuelle Partikel | ○ | ○ | ○ | ● | +| Responsive | ○ | ○ | ○ | ● | +| Spur | ○ | ○ | ○ | ● | +| Zoom | ○ | ○ | ○ | ● | +| Poisson-Scheibe | ○ | ○ | ○ | ● | +| **Pfade** | | | | | +| Beliebiger Pfad | ○ | ○ | ○ | ● (14 Generatoren) | +| **Effekte** | | | | | +| Blase, Filter, Schatten, etc. | ○ | ○ | ○ | ● (5 Effekte) | +| **Easings** | | | | | +| Quad | ○ | ● | ● | ● | +| Back, Bounce, Circ, Cubic, Elastic, Expo, Gaussian, Linear, Quart, Quint, Sigmoid, Sine, Smoothstep | ○ | ○ | ○ | ● | +| **Farb-Plugins** | | | | | +| HEX, HSL, RGB | ● | ● | ● | ● | +| HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH | ○ | ○ | ○ | ● | + +### Bundles mit dedizierter API + +| Funktion | confetti | fireworks | particles | ribbons | +| --------------- | --------------------------------------------------------- | ----------------------- | -------------------------- | ----------------- | +| Formen | Kreis, Herz, Karten, Emoji, Bild, Polygon, Quadrat, Stern | Linie | (von basic) | Ribbon | +| Interaktionen | — | — | Verbindungen + Kollisionen | — | +| Spezial-Plugins | Emitter, Bewegung | Emitter, Töne, Mischung | — | Emitter, Bewegung | +| API-Aufruf | `confetti(opts)` | `fireworks(opts)` | `particles(opts)` | `ribbons(opts)` | + +## Auswahlhilfe + +```mermaid +flowchart TD + A[Schnell starten?] -->|Ja| B[Voreinstellung verwenden?] + A -->|Nein| C[Welche Bundle-Größe?] + B -->|Ja| D["@tsparticles/configs + @tsparticles/slim"] + B -->|Nein| E["Konfetti? → @tsparticles/confetti"] + B -->|Nein| F["Feuerwerk? → @tsparticles/fireworks"] + B -->|Nein| G["Partikel-HG? → @tsparticles/particles"] + B -->|Nein| H["Ribbons? → @tsparticles/ribbons"] + C -->|"Minimal (nur Kreise)"| I["@tsparticles/basic"] + C -->|"Mittel (Formen + Interaktionen)"| J["@tsparticles/slim"] + C -->|"Maximal (alle Funktionen)"| K["tsparticles (loadFull)"] + C -->|"Ganzes Repository"| L["@tsparticles/all"] ``` -Brauchst du CDN-Links und weitere Package-Manager-Varianten? - -- Siehe [`/guide/installation`](/de/guide/installation). - -## Setup-Beispiele - -### Engine + Loader-Bundles (`basic`, `slim`, `full`, `all`) - -```ts -import { tsParticles } from "@tsparticles/engine"; -import { loadSlim } from "@tsparticles/slim"; - -await loadSlim(tsParticles); - -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - number: { value: 80 }, - move: { enable: true, speed: 2 }, - }, - }, -}); +**Faustregeln:** + +1. Die meisten Projekte beginnen mit `@tsparticles/slim`. +2. Wenn die Bundle-Größe entscheidend ist und du nur Kreise brauchst: `@tsparticles/basic`. +3. Wenn du Emitter, Absorber, Text, Wobble/Tilt/Roll brauchst: `tsparticles` mit `loadFull`. +4. Für schnelles Prototyping mit allen Funktionen: `@tsparticles/all`. +5. Für gezielte Effekte (Konfetti, Feuerwerk, Partikel-HG, Ribbons) mit minimalem Setup: dedizierte API-Bundles. + +## Schnellinstallation + +| Bundle | npm-Befehl | Loader-Funktion | CDN-URL | +| ------------------------ | ------------------------------------------------- | ------------------------ | -------------------------------------------------------------- | +| `@tsparticles/basic` | `pnpm add @tsparticles/engine @tsparticles/basic` | `loadBasic(tsParticles)` | `@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| `@tsparticles/slim` | `pnpm add @tsparticles/engine @tsparticles/slim` | `loadSlim(tsParticles)` | `@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| `tsparticles` (full) | `pnpm add @tsparticles/engine tsparticles` | `loadFull(tsParticles)` | `tsparticles@4/tsparticles.bundle.min.js` | +| `@tsparticles/all` | `pnpm add @tsparticles/engine @tsparticles/all` | `loadAll(tsParticles)` | `@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| `@tsparticles/confetti` | `pnpm add @tsparticles/confetti` | `confetti(opts)` | `@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| `@tsparticles/fireworks` | `pnpm add @tsparticles/fireworks` | `fireworks(opts)` | `@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| `@tsparticles/particles` | `pnpm add @tsparticles/particles` | `particles(opts)` | `@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| `@tsparticles/ribbons` | `pnpm add @tsparticles/ribbons` | `ribbons(opts)` | `@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | + +**Hinweis:** Bei basic/slim/full/all-Bundles musst du `load*` VOR `tsParticles.load()` aufrufen. CDN-Dateien machen die Loader-Funktion global verfügbar, rufen sie aber NICHT automatisch auf. Die Confetti/Fireworks/Particles/Ribbons-Bundles haben eigenständige APIs — rufe `confetti()`, `fireworks()` etc. direkt auf. + +CDN-Beispiel für `@tsparticles/slim`: + +```html + + + ``` -Fuer die anderen Presets tauschst du nur Import/Funktion des Loaders: +CDN-Beispiel für `@tsparticles/confetti`: -- `@tsparticles/basic` -> `loadBasic` -- `tsparticles` -> `loadFull` -- `@tsparticles/all` -> `loadAll` - -### Fokussierte APIs (`confetti`, `fireworks`, `particles`, `ribbons`) - -```ts -import { confetti } from "@tsparticles/confetti"; -import { fireworks } from "@tsparticles/fireworks"; -import { particles } from "@tsparticles/particles"; -import { ribbons } from "@tsparticles/ribbons"; - -await confetti({ count: 80, spread: 60 }); -await fireworks({ sounds: false }); -await particles({ count: 100, links: true }); -await ribbons({ count: 5, spread: 0 }); +```html + + ``` -Diese APIs sind ideal, wenn du schnell integrieren willst, ohne viele Engine-Plugins manuell zu verdrahten. - -## Praktische Auswahlregeln - -1. Starte in den meisten Projekten mit `@tsparticles/slim`. -2. Nutze `@tsparticles/basic`, wenn Bundle-Groesse oberste Prioritaet hat und die Features einfach sind. -3. Nutze `tsparticles`, wenn du eine full Basis mit vielen Features und `loadFull` brauchst. -4. Nutze `@tsparticles/all` fuer Prototyping oder wenn du sofort viele Features brauchst. -5. Nutze `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles` oder `@tsparticles/ribbons`, wenn deine UI einen gezielten Effekt mit minimalem Setup braucht. +Siehe auch die [Installationsanleitung](/de/guide/installation) für CDN-, npm-, yarn- und Datei-Details. ## Verwandte Seiten -- Fokussierte Bundles im Playground: [`/playground/bundles`](/de/playground/bundles) -- Einstiegspfad: [`/guide/getting-started`](/de/guide/getting-started) -- Installationsmatrix: [`/guide/installation`](/de/guide/installation) -- Wrapper-Ueberblick: [`/guide/wrappers`](/de/guide/wrappers) +- [Erste Schritte](/de/guide/getting-started) +- [Installationsanleitung](/de/guide/installation) +- [Voreinstellungskatalog](/de/demos/presets) +- [Palettenkatalog](/de/demos/palettes) +- [Formenkatalog](/de/demos/shapes) diff --git a/websites/website/docs/de/guide/color-formats.md b/websites/website/docs/de/guide/color-formats.md index 466530f98ae..d57784853ff 100644 --- a/websites/website/docs/de/guide/color-formats.md +++ b/websites/website/docs/de/guide/color-formats.md @@ -1,6 +1,6 @@ # Farbformate -tsParticles akzeptiert mehrere Farbformate über Optionen wie `background`, `particles.color` und Plugin-Einstellungen. +tsParticles akzeptiert mehrere Farbformate über Optionen wie `background`, `particles.paint` und Plugin-Einstellungen. ## Gängige Formate diff --git a/websites/website/docs/de/guide/getting-started.md b/websites/website/docs/de/guide/getting-started.md index 02f974bf45b..8d4caf275e4 100644 --- a/websites/website/docs/de/guide/getting-started.md +++ b/websites/website/docs/de/guide/getting-started.md @@ -1,107 +1,197 @@ # Erste Schritte -Dieser Pfad ist das schnellste und zuverlässigste Setup für `tsParticles` im Jahr 2026. +tsParticles ist eine JavaScript/TypeScript-Bibliothek zum Erstellen von Partikelanimationen, Konfetti, Feuerwerk und mehr. Sie funktioniert in jedem modernen Browser und ist sowohl als npm-Paket als auch über CDN mit ` + + + + +
+ + + +``` -- `@tsparticles/particles`: Vereinfachte Partikel-Hintergrund-API -- `@tsparticles/confetti`: Konfetti-API mit einem Aufruf -- `@tsparticles/fireworks`: Feuerwerks-API mit einem Aufruf +> **Hinweis**: Auch bei CDN-Bundles MUSST du `loadSlim(tsParticles)` (oder `loadBasic` / `loadFull` / `loadAll`) vor `tsParticles.load()` aufrufen. CDN-Bundles machen die Loader-Funktion global verfügbar, rufen sie aber NICHT automatisch auf. -## 5) Verwenden Sie Voreinstellungen/Konfigurationen, wenn Sie Geschwindigkeit benötigen +Das gleiche Muster gilt für `@tsparticles/basic` → `loadBasic`, `tsparticles` → `loadFull`, `@tsparticles/all` → `loadAll`. -Wenn Sie vorgefertigte Effekte bevorzugen: +### Pfad C — Spezialisierte Bundles mit dedizierter API (Confetti, Fireworks, Particles) + +Einige Bundles haben ihre eigene vereinfachte API, ohne `tsParticles.load()` verwenden zu müssen: + +```html + + + + + + + + + +``` + +Gleiches gilt für `fireworks()`, `particles()`, `ribbons()`. + +## Welches Bundle wählen? + +| Bundle | npm | Verwendung | +| ------------------------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | +| `@tsparticles/basic` | `loadBasic(tsParticles)` | Minimum: Kreise, Bewegung, Opazität, Größe. Keine Interaktionen. | +| `@tsparticles/slim` | `loadSlim(tsParticles)` | **Empfohlen für die meisten Projekte.** Fügt Interaktionen (Klick/Hover), Partikelverbindungen, Bilder, Sterne, Polygone hinzu. | +| `tsparticles` | `loadFull(tsParticles)` | Vollständiger offizieller Funktionsumfang: Emitter, Absorber, Textformen, Roll, Wobble, Trail. | +| `@tsparticles/all` | `loadAll(tsParticles)` | **Alles** im Repository: jede Form, Interaktion, Effekt, Easing, Pfad, Export. Nur zum Prototyping. | +| `@tsparticles/confetti` | `confetti(options)` | Konfetti in einem Funktionsaufruf. Dedizierte API. | +| `@tsparticles/fireworks` | `fireworks(options)` | Feuerwerk in einem Funktionsaufruf. Dedizierte API. | +| `@tsparticles/particles` | `particles(options)` | Vereinfachter Partikel-Hintergrund. Dedizierte API. | +| `@tsparticles/ribbons` | `ribbons(options)` | Ribbon-Effekt. Dedizierte API. | + +Weitere Details: [`/guide/bundles`](/de/guide/bundles). + +## Voreinstellungen verwenden + +Das Paket `@tsparticles/configs` enthält Dutzende vorgefertigter Konfigurationen (Absorber, Blasen, Schnee, Sterne, Schwerkraft, Kollisionen etc.). ```bash -pnpm add @tsparticles/configs +pnpm add @tsparticles/engine @tsparticles/slim @tsparticles/configs ``` -Laden Sie dann eine Konfiguration per Schlüssel, z. B. die [`demo/vite`-App](https://github.com/tsparticles/tsparticles/blob/main/demo/vite/src/main.ts). +```ts +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import "@tsparticles/configs"; + +await loadSlim(tsParticles); + +await tsParticles.load({ + id: "tsparticles", + options: { preset: "snow" }, +}); +``` -Wenn Sie Setups bevorzugen, die auf Preset-Namen basieren, verwenden Sie den offiziellen Preset-Katalog in [`/demos/presets`](/de/demos/presets). +Mit CDN: -## Schnelle Dokumentationskarte +```html + + + + +``` -- Root-Optionen: [`/options/`](/de/options/) -- Wrapper-Referenz: [`/guide/wrappers`](/de/guide/wrappers) +## Kurzreferenzen + +- Optionsdokumentation: [`/options/`](/de/options/) +- Bundle-Anleitung: [`/guide/bundles`](/de/guide/bundles) - Voreinstellungskatalog: [`/demos/presets`](/de/demos/presets) - Palettenkatalog: [`/demos/palettes`](/de/demos/palettes) - Formenkatalog: [`/demos/shapes`](/de/demos/shapes) -- Migration von particles.js: [`/migrations/particles-js`](/de/migrations/particles-js) +- Framework-Wrapper: [`/guide/wrappers`](/de/guide/wrappers) - Farbformate: [`/guide/color-formats`](/de/guide/color-formats) - Container-Lebenszyklus: [`/guide/container-lifecycle`](/de/guide/container-lifecycle) -- Plugins und Anpassungen: [`/guide/plugins-customization`](/de/guide/plugins-customization) +- Plugins & Anpassungen: [`/guide/plugins-customization`](/de/guide/plugins-customization) ## Fehlerbehebung -- Leerer Bildschirm: Überprüfen Sie, ob `#tsparticles` vorhanden ist, bevor Sie `tsParticles.load` aufrufen. - -- Fehlende Funktion: Sie benötigen wahrscheinlich ein anderes Plugin/Paket (Form, Interaktion, Updater). -- Tippfehler bei den Optionen: Halten Sie Ihre Pakete auf die gleiche Haupt-/Nebenversion ausgerichtet. +| Problem | Wahrscheinliche Ursache | Lösung | +| ------------------------------------------------------ | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| Leerer Bildschirm, keine Partikel | `#tsparticles` existiert nicht im DOM beim Aufruf von `tsParticles.load()` | Stelle sicher, dass das DIV vor dem Skript existiert, oder verwende `DOMContentLoaded` | +| Leerer Bildschirm, keine Partikel | Nur `@tsparticles/engine` installiert | Installiere auch ein Bundle (`@tsparticles/slim`) oder Plugins — die Engine allein hat keine Formen zum Zeichnen | +| Fehler "loadBasic/loadSlim/loadFull is not a function" | Bundle nicht installiert oder falscher Import | `pnpm add @tsparticles/slim` und importiere `{ loadSlim }` | +| Partikel bewegen sich nicht | `move.enable` nicht auf `true` gesetzt | Füge `move: { enable: true, speed: 2 }` hinzu | +| Fehlende Funktion (z.B. Links, Kollisionen) | Gewähltes Bundle enthält sie nicht | Wechsle zu einem umfangreicheren Bundle (`@tsparticles/slim` oder `tsparticles`) oder installiere das spezifische Plugin | +| TypeScript-Typfehler | Paketversionen nicht synchron | Halte Engine und Bundle auf derselben Haupt-/Nebenversion | diff --git a/websites/website/docs/de/guide/installation.md b/websites/website/docs/de/guide/installation.md index 287f95b99c8..97e9c2d53a7 100644 --- a/websites/website/docs/de/guide/installation.md +++ b/websites/website/docs/de/guide/installation.md @@ -1,109 +1,146 @@ # Installation -Diese Seite ubernimmt die Installationsmatrix aus dem Haupt-README von `tsParticles`. - -Offizielle Referenz: - ## Wähle deinen Weg -- **Schneller Standard**: `@tsparticles/engine` + `@tsparticles/slim` -- **Leichteres Custom-Runtime**: `@tsparticles/engine` + nur benotigte Plugins -- **Fokussierte APIs**: `@tsparticles/particles`, `@tsparticles/confetti`, `@tsparticles/fireworks` oder `@tsparticles/ribbons` -- **Alle Features enthalten**: `@tsparticles/all` - -## Hosting / CDN - -Nutze einen dieser Anbieter (oder hoste die gebauten Dateien selbst). +| Szenario | Befehl | +| ----------------------------- | ------------------------------------------------- | +| Schnellstart (empfohlen) | `pnpm add @tsparticles/engine @tsparticles/slim` | +| Minimales Setup | `pnpm add @tsparticles/engine @tsparticles/basic` | +| Vollständiger Funktionsumfang | `pnpm add @tsparticles/engine tsparticles` | +| Alles im Repository | `pnpm add @tsparticles/engine @tsparticles/all` | +| Nur Konfetti | `pnpm add @tsparticles/confetti` | +| Nur Feuerwerk | `pnpm add @tsparticles/fireworks` | +| Partikel-Hintergrund | `pnpm add @tsparticles/particles` | +| Ribbon-Effekt | `pnpm add @tsparticles/ribbons` | -### jsDelivr +> **Wichtig**: `@tsparticles/engine` allein zeichnet nichts. Du musst immer ein Bundle (zum Laden von Formen und Animationen) oder einzelne Plugins hinzufügen. Siehe die [Bundle-Anleitung](/de/guide/bundles). -- -- -- -- -- -- -- -- +## npm -### cdnjs +```bash +# Engine + Slim (empfohlen für die meisten Projekte) +npm install @tsparticles/engine @tsparticles/slim -- +# Engine + Basic (minimal) +npm install @tsparticles/engine @tsparticles/basic -### unpkg +# Engine + Full (tsparticles) +npm install @tsparticles/engine tsparticles -- -- -- -- -- -- -- -- +# Engine + All +npm install @tsparticles/engine @tsparticles/all -## Installation per Package-Manager +# Dedizierte API-Bundles (keine explizite Engine nötig) +npm install @tsparticles/confetti +npm install @tsparticles/fireworks +npm install @tsparticles/particles +npm install @tsparticles/ribbons +``` -### npm +## yarn ```bash -npm install @tsparticles/engine +yarn add @tsparticles/engine @tsparticles/slim +# ... gleiches Muster für andere Bundles ``` -### yarn +## pnpm ```bash -yarn add @tsparticles/engine +pnpm add @tsparticles/engine @tsparticles/slim +# ... gleiches Muster für andere Bundles ``` -### pnpm +## CDN (Script-Tags) -```bash -pnpm add @tsparticles/engine -``` +Alle Pakete sind auf jsDelivr, unpkg und cdnjs verfügbar. -## Import und require +### jsDelivr -```ts -const tsParticles = require("@tsparticles/engine"); +| Bundle | URL | +| --------------------------- | ------------------------------------------------------------------------------------------- | +| Engine | `https://cdn.jsdelivr.net/npm/@tsparticles/engine@4/tsparticles.engine.min.js` | +| Basic | `https://cdn.jsdelivr.net/npm/@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| Slim | `https://cdn.jsdelivr.net/npm/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| Full (`tsparticles`) | `https://cdn.jsdelivr.net/npm/tsparticles@4/tsparticles.bundle.min.js` | +| All | `https://cdn.jsdelivr.net/npm/@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| Confetti | `https://cdn.jsdelivr.net/npm/@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| Fireworks | `https://cdn.jsdelivr.net/npm/@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| Particles | `https://cdn.jsdelivr.net/npm/@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| Ribbons | `https://cdn.jsdelivr.net/npm/@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | +| particles.js-Kompatibilität | `https://cdn.jsdelivr.net/npm/@tsparticles/pjs@4/tsparticles.pjs.min.js` | -// or +### unpkg -import { tsParticles } from "@tsparticles/engine"; -``` +Gleiche Struktur: `https://unpkg.com/{paketname}@{version}/{dateiname}` -## Minimales Runtime-Setup (`@tsparticles/slim`) +Beispiel: +`https://unpkg.com/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` + +### cdnjs + +`https://cdnjs.com/libraries/tsparticles` + +## Importbeispiele + +### Mit Bundler (ES-Modul-Import) ```ts +// Engine + Bundle-Loader import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; await loadSlim(tsParticles); +await tsParticles.load({ id: "tsparticles", options: { ... } }); +``` -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - move: { - enable: true, - }, - number: { - value: 60, - }, - }, - }, -}); +### Mit CommonJS (require) + +```ts +const { tsParticles } = require("@tsparticles/engine"); +const { loadSlim } = require("@tsparticles/slim"); + +(async () => { + await loadSlim(tsParticles); + await tsParticles.load({ id: "tsparticles", options: { ... } }); +})(); ``` -## Verwandte Seiten +### Mit CDN (Script-Tag) + +```html + + + + + + +``` -- [`/guide/getting-started`](/de/guide/getting-started) -- [`/guide/wrappers`](/de/guide/wrappers) -- [`/demos/presets`](/de/demos/presets) -- [`/migrations/particles-js`](/de/migrations/particles-js) +Mit dedizierten API-Bundles: -## Legacy-Kompatibilitat +```html + + +``` -Wenn du alte particles.js-Integrationen migrierst, nutze das Kompatibilitatspaket: +## Verwandte Seiten -- npm: -- jsDelivr: +- [Erste Schritte](/de/guide/getting-started) +- [Bundle-Anleitung](/de/guide/bundles) +- [Framework-Wrapper](/de/guide/wrappers) diff --git a/websites/website/docs/de/guides/angular.md b/websites/website/docs/de/guides/angular.md new file mode 100644 index 00000000000..ab979aba5c9 --- /dev/null +++ b/websites/website/docs/de/guides/angular.md @@ -0,0 +1,631 @@ +--- +title: Angular-Integration +description: Schritt-für-Schritt-Anleitung zur Integration von tsParticles in Angular-Anwendungen mit @tsparticles/angular. +--- + +# Angular-Integration + +Das Paket `@tsparticles/angular` bietet Angular-Komponenten, Module und Dienste für tsParticles. Diese Anleitung behandelt sowohl den traditionellen `NgModule`-Ansatz als auch Angular 17+ Standalone-Komponenten. + +--- + +## Installation + +```bash +npm install @tsparticles/angular @tsparticles/engine +``` + +Für den vollen Funktionsumfang das vollständige Bundle installieren: + +```bash +npm install tsparticles +``` + +Optionale Preset-Pakete: + +```bash +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +``` + +--- + +## Grundlegende Verwendung (NgModule) + +### 1. Modul importieren + +```typescript +import { NgModule } from "@angular/core"; +import { BrowserModule } from "@angular/platform-browser"; +import { NgParticlesModule } from "@tsparticles/angular"; +import { AppComponent } from "./app.component"; + +@NgModule({ + declarations: [AppComponent], + imports: [BrowserModule, NgParticlesModule], + bootstrap: [AppComponent], +}) +export class AppModule {} +``` + +### 2. Engine initialisieren + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d47a1", + }, + fpsLimit: 120, + particles: { + number: { + value: 80, + }, + color: { + value: "#ffffff", + }, + shape: { + type: "circle", + }, + opacity: { + value: 0.5, + }, + size: { + value: { min: 1, max: 5 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Particles-Container geladen", container); + } +} +``` + +### 3. Template + +```html + +``` + +--- + +## Details zur Engine-Initialisierung + +Die Methode `NgParticlesService.init()` muss genau einmal aufgerufen werden, typischerweise in `AppComponent.ngOnInit()`. Sie erhält einen Callback, in dem die Plugins/Presets geladen werden, die Ihre Anwendung benötigt. + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesService } from "@tsparticles/angular"; +import type { Engine } from "@tsparticles/engine"; + +@Component({ ... }) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + // Nur laden, was für kleinere Bundles benötigt wird + await loadBasic(engine); // Grundformen + Bewegung + await loadEmittersPlugin(engine); // Emitter-Formen + }); + } +} +``` + +Verfügbare Ladefunktionen aus `tsparticles`: + +| Funktion | Beschreibung | +| ------------------- | ------------------------------------------- | +| `loadFull(engine)` | Alle Funktionen (größtes Bundle) | +| `loadBasic(engine)` | Kernformen (Kreis, Quadrat, Polygon usw.) | +| `loadSlim(engine)` | Die meisten Funktionen ohne seltene Plugins | +| `loadAll(engine)` | Veralteter Alias für `loadFull` | + +--- + +## Konfetti-Effekt + +```bash +npm install @tsparticles/preset-confetti +``` + +```typescript +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// Im NgParticlesService.init-Callback: +await loadConfettiPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "confetti", + background: { + color: "transparent", + }, +}; +``` + +Oder verwenden Sie die praktische ``-Komponente: + +```typescript +// app.module.ts +import { NgParticlesModule } from "@tsparticles/angular"; + +@NgModule({ + imports: [NgParticlesModule], +}) +export class AppModule {} +``` + +```html + +``` + +--- + +## Feuerwerks-Effekt + +```bash +npm install @tsparticles/preset-fireworks +``` + +```typescript +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; + +// Im NgParticlesService.init-Callback: +await loadFireworksPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "fireworks", + background: { + color: "#000000", + }, +}; +``` + +Oder verwenden Sie die ``-Komponente: + +```html + +``` + +> Vermeiden Sie den automatischen Start von Feuerwerk; binden Sie es an eine Benutzeraktion (Klick, Scrollen), um unnötige Ressourcennutzung zu vermeiden. + +--- + +## Benutzerdefinierte Partikel-Konfiguration + +Voll ausgestattete benutzerdefinierte Partikeleinrichtung mit Interaktivität: + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-particles", + templateUrl: "./particles.component.html", +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d0d0d", + }, + fpsLimit: 60, + particles: { + number: { + value: 100, + density: { + enable: true, + }, + }, + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + shape: { + type: ["circle", "square", "triangle"], + }, + opacity: { + value: 0.8, + random: true, + anim: { + enable: true, + speed: 1, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + random: true, + anim: { + enable: true, + speed: 4, + size_min: 1, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.3, + width: 1, + triangles: { + enable: true, + color: "#ffffff", + opacity: 0.05, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { + enable: true, + rotateX: 600, + rotateY: 600, + }, + }, + life: { + duration: { + value: 5, + random: true, + }, + count: 0, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: { + enable: true, + }, + }, + modes: { + grab: { + distance: 200, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + detectRetina: true, + }; + + particlesLoaded(container: Container): void { + console.log("Container geladen", container); + } +} +``` + +```html + +``` + +--- + +## Ereignisse + +Die `ngx-particles`-Komponente sendet das `particlesLoaded`-Ereignis: + +```typescript +import type { Container } from "@tsparticles/engine"; + +// Komponentenmethode +onParticlesLoaded(container: Container): void { + // Zugriff auf die Container-API + container.pause(); + container.play(); + container.destroy(); + container.exportImage().then((blob) => { /* ... */ }); +} +``` + +```html + +``` + +Die Container-Referenz gibt Ihnen volle programmatische Kontrolle: Anhalten, Fortsetzen, Zerstören, Exportieren und mehr. + +--- + +## Template-Syntax & Bedingtes Rendern + +Verwenden Sie Angular-Strukturdirektiven zum Ein-/Ausblenden der Komponente: + +```html + + + +``` + +```typescript +export class AppComponent { + showParticles = true; + // ... +} +``` + +Wenn `*ngIf` auf `false` ausgewertet wird, wird die Komponente zerstört (einschließlich der Canvas und aller Partikelinstanzen). Beim erneuten Erstellen wird alles von Grund auf neu initialisiert. + +--- + +## Standalone-Komponenten (Angular 17+) + +In Angular 17+ können Sie `NgParticlesModule` direkt in eine Standalone-Komponente importieren: + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesModule, NgParticlesService } from "@tsparticles/angular"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +@Component({ + selector: "app-particles", + standalone: true, + imports: [NgParticlesModule], + template: ` + + `, +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 50 }, + color: { value: "#fff" }, + shape: { type: "circle" }, + move: { enable: true, speed: 2 }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Geladen", container); + } +} +``` + +Kein `NgModule`-Wrapper erforderlich — einfach `NgParticlesModule` im `imports`-Array der Komponente importieren. + +--- + +## Vollständiges Komponenten-Beispiel + +### app.component.ts + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + title = "tsParticles Angular-Demo"; + + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadSlim(engine); + }); + } + + particlesOptions: ISourceOptions = { + autoPlay: true, + background: { + color: "#1e1e2e", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMask: { + cover: { + color: "#1e1e2e", + }, + enable: false, + }, + fullScreen: { + enable: true, + zIndex: -1, + }, + detectRetina: true, + fpsLimit: 60, + particles: { + color: { + value: "#cdd6f4", + }, + links: { + color: "#cdd6f4", + distance: 150, + enable: true, + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1, + }, + number: { + value: 60, + }, + opacity: { + value: 0.6, + }, + size: { + value: { min: 1, max: 3 }, + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Partikel geladen", container); + } +} +``` + +### app.component.html + +```html +
+ + +
+

{{ title }}

+

Partikel laufen im Hintergrund.

+
+
+``` + +### app.component.css + +```css +:host { + display: block; + width: 100%; + height: 100%; +} +``` + +--- + +## API-Referenz + +| Komponente | Selektor | Beschreibung | +| ---------- | --------------- | ----------------------------------- | +| Particles | `ngx-particles` | Vollständiges Partikelsystem | +| Confetti | `ngx-confetti` | Vorkonfigurierter Konfetti-Effekt | +| Fireworks | `ngx-fireworks` | Vorkonfigurierter Feuerwerks-Effekt | + +### `ngx-particles` Eingaben + +| Eingabe | Typ | Standard | Beschreibung | +| --------- | ---------------- | --------------- | ------------------------------ | +| `id` | `string` | `"tsparticles"` | Canvas-Element-ID | +| `options` | `ISourceOptions` | `{}` | Partikel-Konfiguration | +| `url` | `string` | — | Remote-JSON-Konfigurations-URL | + +### `ngx-particles` Ausgaben + +| Ausgabe | Payload | Beschreibung | +| ----------------- | ----------- | ----------------------------------------------------- | +| `particlesLoaded` | `Container` | Wird ausgegeben, wenn der Container initialisiert ist | + +--- + +## Fehlerbehebung + +- **Leere / unsichtbare Canvas** — Stellen Sie sicher, dass das übergeordnete Element eine definierte Höhe hat (z. B. `height: 100vh`). Die Canvas übernimmt die Container-Abmessungen. +- **`NgParticlesService.init()` mehrfach aufgerufen** — Nur einmal aufrufen, typischerweise in `AppComponent.ngOnInit()`. Nachfolgende Aufrufe sind sicher, aber überflüssig. +- **Modul nicht gefunden** — Überprüfen Sie, ob `@tsparticles/angular` in den `package.json`-Abhängigkeiten aufgeführt ist und dass Sie `NgParticlesModule` importiert haben. +- **`NullInjectorError: No provider for NgParticlesService`** — Sie müssen `NgParticlesModule` importieren (oder re-exportieren) in dem Modul, in dem Sie die Komponente bereitstellen. diff --git a/websites/website/docs/de/guides/astro.md b/websites/website/docs/de/guides/astro.md new file mode 100644 index 00000000000..59a0f7ee3dc --- /dev/null +++ b/websites/website/docs/de/guides/astro.md @@ -0,0 +1,384 @@ +# Astro-Integration + +Verwenden Sie tsParticles auf Ihrer Astro-Seite mit dem offiziellen `@tsparticles/astro`-Integrationspaket. + +## Installation + +Installieren Sie die Astro-Integration und den tsParticles-Kern über Ihren Paketmanager: + +```bash +npm install @tsparticles/astro tsparticles +``` + +```bash +pnpm add @tsparticles/astro tsparticles +``` + +```bash +yarn add @tsparticles/astro tsparticles +``` + +## Engine-Initialisierung + +tsParticles verwendet eine modulare Architektur. Bevor Partikel gerendert werden, müssen Sie die Engine mit den benötigten Funktionen initialisieren. Erstellen Sie ein Client-Script (z. B. `src/scripts/particles-init.ts`) oder verwenden Sie ein Inline-` +``` + +> Die `id`-Eigenschaft wird an den zugrunde liegenden Canvas-Container `
` weitergegeben. Verwenden Sie sie für Styling oder den imperativen Zugriff via `document.getElementById()`. + +## TypeScript-Unterstützung + +Die Integration enthält vollständige TypeScript-Deklarationen. Verwenden Sie `ISourceOptions` von `@tsparticles/engine`, um Ihre Konfiguration zu typisieren: + +```typescript +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { + value: 50, + density: { enable: true }, + }, + opacity: { value: 0.5 }, + shape: { type: "circle" }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + repulse: { distance: 200 }, + }, + }, +}; +``` + +## Benutzerdefinierte Konfiguration + +Nachfolgend eine umfangreichere Konfiguration, die Sie in jede Astro-Seite einfügen können: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + autoPlay: true, + background: { + color: "#0d47a1", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMode: { + enable: true, + zIndex: -1, + }, + fpsLimit: 120, + particles: { + color: { + value: "#ffffff", + animation: { + enable: true, + speed: 20, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + triangles: { + enable: true, + opacity: 0.1, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "out", + attract: { enable: false }, + }, + number: { + value: 80, + density: { + enable: true, + }, + }, + opacity: { + value: 0.5, + animation: { + enable: true, + speed: 1, + sync: false, + }, + }, + shape: { + type: "circle", + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 3, + sync: false, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: true, + }, + modes: { + grab: { + distance: 200, + links: { opacity: 0.5 }, + }, + push: { quantity: 4 }, + }, + }, + detectRetina: true, +}; +--- + + + + +``` + +## Presets verwenden + +Statt eine Konfiguration manuell zu erstellen, laden Sie ein Preset während der Engine-Initialisierung und referenzieren Sie es in den Optionen: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + preset: "stars", + background: { color: "#000000" }, +}; +--- + + + + +``` + +## Integration mit anderen Frameworks + +Da Astro UI-Frameworks wie React, Vue, Svelte und Solid unterstützt, können Sie die frameworkspezifische tsParticles-Komponente in `.astro`-Dateien verwenden: + +### React in Astro + +```astro +--- +import Particles from "@tsparticles/react"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +### Vue in Astro + +```astro +--- +import Particles from "@tsparticles/vue3"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +> Die Direktive `client:load` teilt Astro mit, die Komponente sofort beim Seitenladen zu hydrieren. Verwenden Sie `client:visible` für verzögertes Laden. + +## Vollständiges Seiten-Beispiel + +Eine vollständige Astro-Seite mit Partikeln als animiertem Hintergrund: + +```astro +--- +import Layout from "../layouts/Layout.astro"; +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + number: { value: 100 }, + color: { value: "#ffffff" }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + size: { + value: { min: 1, max: 4 }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, +}; +--- + + +
+

Willkommen

+

Diese Seite hat einen Partikel-Hintergrund, betrieben von tsParticles.

+
+ +
+ + + + +``` + +## Komponenten-Eigenschaften + +| Eigenschaft | Typ | Standard | Beschreibung | +| -------------------- | ---------------- | ------------------------- | ------------------------------------------------ | +| `id` | `string` | `"tsparticles"` | DOM-Element-ID für den Container | +| `options` | `ISourceOptions` | `{}` | Vollständiges tsParticles-Konfigurationsobjekt | +| `url` | `string` | — | Konfiguration von einer Remote-JSON-URL laden | +| `particlesClassName` | `string` | `"tsparticles-canvas-el"` | CSS-Klasse für das Canvas-Element | +| `container` | `object` | — | Vorhandene `Container`-Instanz (fortgeschritten) | diff --git a/websites/website/docs/de/guides/ember.md b/websites/website/docs/de/guides/ember.md new file mode 100644 index 00000000000..fa8e00bcdf6 --- /dev/null +++ b/websites/website/docs/de/guides/ember.md @@ -0,0 +1,346 @@ +--- +title: Ember-Anleitung +description: Vollständige Anleitung zur Integration von tsParticles mit Ember.js-Anwendungen. +--- + +# Ember-Anleitung + +## Inhaltsverzeichnis + +1. [Installation](#installation) +2. [Engine-Initialisierung](#engine-initialization) +3. [Grundlegende Verwendung](#basic-usage) +4. [Benutzerdefinierte Konfiguration](#custom-configuration) +5. [Ereignisbehandlung](#event-handling) +6. [Bedingtes Rendern](#conditional-rendering) +7. [TypeScript-Beispiel](#typescript-example) + +--- + +## Installation + +Installieren Sie das Ember-Addon und die tsParticles-Engine über ember-cli: + +```bash +ember install @tsparticles/ember +``` + +Dies installiert das Addon und seine Peer-Abhängigkeit `tsparticles`. Sie können optional Preset-Pakete hinzufügen: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Engine-Initialisierung + +Das Addon exportiert ein `initParticlesEngine`-Dienstprogramm, das Sie einmal auf Anwendungsebene aufrufen. Es erhält einen asynchronen Callback, in dem Sie die benötigten Funktionen, Presets oder Formen laden. + +```typescript +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadFull } from "tsparticles"; + +// Rufen Sie dies während des Anwendungs-Bootstraps auf +if (typeof window !== "undefined") { + void initParticlesEngine(async (engine) => { + await loadFull(engine); + }); +} +``` + +Typische Orte für diesen Aufruf sind der `beforeModel`-Hook der Anwendungsroute, der Konstruktor eines Anwendungs-Controllers oder ein Instance-Initializer. Die Engine-Singleton wird einmal initialisiert und von allen ``-Komponenten in Ihrer App gemeinsam genutzt. + +--- + +## Grundlegende Verwendung + +Nach der Initialisierung der Engine verwenden Sie die ``-Komponente in einer beliebigen Vorlage. Übergeben Sie Ihre Partikel-Konfiguration über das `@options`-Argument. + +```hbs +{{! app/templates/application.hbs }} + + +``` + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, + }; +} +``` + +--- + +## Benutzerdefinierte Konfiguration + +Erstellen Sie eine umfangreichere Konfiguration mit Interaktivität, mehreren Formen und responsiver Dichte. + +```typescript +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class IndexController extends Controller { + options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, + }; +} +``` + +```hbs + +``` + +--- + +## Ereignisbehandlung + +Die ``-Komponente feuert eine `@particlesLoaded`-Aktion, wenn der Container die Initialisierung abgeschlossen hat und der erste Frame gerendert wird. Verwenden Sie dies, um auf die `Container`-Instanz für programmatische Steuerung zuzugreifen. + +```typescript +import Controller from "@ember/controller"; +import { action } from "@ember/object"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + /* ... */ + }; + + @action + loadedCallback(container: Container) { + console.log("Partikel geladen", container.id); + + // Beispiel für programmatische Steuerung: + setTimeout(() => { + container.pause(); + console.log("Partikel nach 5 Sekunden pausiert"); + }, 5000); + } +} +``` + +```hbs + +``` + +Sie können das Callback-Muster auch inline mit einem Template-Helper verwenden, wenn Sie keine separate Aktion definieren möchten. + +--- + +## Bedingtes Rendern + +Verwenden Sie Embers `{{if}}`-Helper zusammen mit einer `@tracked`-Eigenschaft, um zu steuern, wann die ``-Komponente gerendert wird. Dies ist nützlich, wenn die Engine-Initialisierung asynchron ist und Sie vermeiden möchten, die Komponente vor der Bereitschaft der Engine zu rendern. + +```typescript +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked engineReady = false; + + options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { enable: true, speed: 1, outModes: { default: "bounce" } }, + }, + background: { color: "#1a1a2e" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } +} +``` + +```hbs +{{#if this.engineReady}} + +{{else}} +

Lade Partikel...

+{{/if}} +``` + +Der `@tracked`-Dekorator stellt sicher, dass die Vorlage automatisch neu gerendert wird, sobald das Promise aufgelöst wird. + +--- + +## TypeScript-Beispiel + +Nachfolgend ein vollständiger, typisierter Ember-Anwendungs-Controller, der das vollständige Integrationsmuster mit Slim-Preset, Interaktivität und Lebenszyklus-Management demonstriert. + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked private engineReady = false; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } + + @action + private handleParticlesLoaded(container: Container): void { + this.container = container; + console.log("Partikel geladen in Container:", container.id); + } +} +``` + +```hbs +{{! app/templates/application.hbs }} + +{{#if this.engineReady}} +
+

tsParticles + Ember

+ +
+{{else}} +
+

Initialisiere Partikel-Engine...

+
+{{/if}} +``` + +--- + +Sie haben jetzt alles, was Sie benötigen, um tsParticles in eine Ember.js-Anwendung zu integrieren. Jedes Beispiel ist in sich geschlossen und kann direkt in Ihr Projekt kopiert werden. diff --git a/websites/website/docs/de/guides/index.md b/websites/website/docs/de/guides/index.md new file mode 100644 index 00000000000..8b81a1af742 --- /dev/null +++ b/websites/website/docs/de/guides/index.md @@ -0,0 +1,58 @@ +--- +title: Schritt-für-Schritt-Anleitungen +description: Entdecken Sie frameworkspezifische Anleitungen zur Integration von tsParticles in Ihr Projekt. +--- + +# Schritt-für-Schritt-Anleitungen + +Willkommen im tsParticles-Anleitungsbereich. Egal, ob Sie eine statische Vanilla-JS-Seite, eine Single-Page-App in React oder Vue oder eine Full-Stack-Anwendung mit Next.js oder Nuxt erstellen, diese Schritt-für-Schritt-Tutorials führen Sie durch Installation, grundlegende Verwendung, erweiterte Konfigurationen und interaktive Effekte. + +Jede Anleitung ist in sich geschlossen und enthält kopierbare Code-Beispiele, damit Sie schnell loslegen können. + +## Verfügbare Anleitungen + +| Framework / Wrapper | Paket | Beschreibung | +| --------------------------------- | ------------------------------------ | --------------------------------------------------- | +| [Vanilla JS](./vanilla) | `tsparticles` (CDN oder npm) | Direkte DOM-Integration mit `tsParticles.load()` | +| [React](./react) | `@tsparticles/react` | Offizieller React-Wrapper mit Hooks und Komponenten | +| [Vue 3](./vue3) | `@tsparticles/vue3` | Offizielles Vue-3-Plugin mit Composables | +| [Angular](./angular) | `@tsparticles/angular` | Offizielle Angular-Komponente und -Modul | +| [Svelte](./svelte) | `@tsparticles/svelte` | Offizielle Svelte-Komponente | +| [Next.js](./nextjs) | `@tsparticles/react` (mit Next.js) | Serverseitiges Rendern und dynamische Importe | +| [Nuxt](./nuxt) | `@tsparticles/vue3` (mit Nuxt) | SSR-sichere Integration als Nuxt-Plugin | +| [Solid](./solid) | `@tsparticles/solid` | Offizieller SolidJS-Wrapper | +| [Preact](./preact) | `@tsparticles/preact` | Preact-kompatible Komponente | +| [Lit](./lit) | `@tsparticles/lit` | Lit-Webkomponenten-Wrapper | +| [Qwik](./qwik) | `@tsparticles/qwik` | Qwik-optimierte Integration | +| [jQuery](./jquery) | `@tsparticles/jquery` | jQuery-Plugin für Legacy-Projekte | +| [Astro](./astro) | `@tsparticles/react` (oder beliebig) | Island-Architektur mit Client-Direktiven | +| [Web Components](./webcomponents) | `@tsparticles/webcomponents` | Custom-Elements-API-Integration | +| [Stencil](./stencil) | `@tsparticles/stencil` | Stencil-Komponenten-Wrapper | +| [Ember](./ember) | `@tsparticles/ember` | Ember-Addon-Integration | +| [Riot](./riot) | `@tsparticles/riot` | Riot.js-Wrapper | +| [Inferno](./inferno) | `@tsparticles/inferno` | Inferno-kompatible Komponente | +| [WordPress](./wordpress) | Plugin + `tsparticles` | Block-Editor-/Shortcode-Integration | + +## Wählen Sie Ihre Anleitung + +- [Vanilla JS (reines JavaScript)](./vanilla) +- [React](./react) +- [Vue 3](./vue3) +- [Angular](./angular) +- [Svelte](./svelte) +- [Next.js](./nextjs) +- [Nuxt](./nuxt) +- [Solid](./solid) +- [Preact](./preact) +- [Lit](./lit) +- [Qwik](./qwik) +- [jQuery](./jquery) +- [Astro](./astro) +- [Web Components](./webcomponents) +- [Stencil](./stencil) +- [Ember](./ember) +- [Riot](./riot) +- [Inferno](./inferno) +- [WordPress](./wordpress) + +Viel Erfolg beim Erstellen! diff --git a/websites/website/docs/de/guides/inferno.md b/websites/website/docs/de/guides/inferno.md new file mode 100644 index 00000000000..a8065d1d4be --- /dev/null +++ b/websites/website/docs/de/guides/inferno.md @@ -0,0 +1,373 @@ +--- +title: Inferno-Anleitung +description: Vollständige Anleitung zur Integration von tsParticles mit Inferno-Anwendungen. +--- + +# Inferno-Anleitung + +## Inhaltsverzeichnis + +1. [Installation](#installation) +2. [Grundlegende Verwendung](#basic-usage) +3. [Engine-Initialisierung](#engine-initialization) +4. [Benutzerdefinierte Konfiguration](#custom-configuration) +5. [Preset-Verwendung](#preset-usage) +6. [Komponenten-Muster](#component-pattern) +7. [TypeScript-Beispiel](#typescript-example) + +--- + +## Installation + +Installieren Sie den Inferno-Wrapper und die tsParticles-Engine über npm: + +```bash +npm install @tsparticles/inferno tsparticles +``` + +Optional das Slim-Preset für ein kleineres Bundle installieren: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Grundlegende Verwendung + +Das Paket `@tsparticles/inferno` exportiert zwei Elemente: `ParticlesProvider` und `Particles`. Umwickeln Sie Ihre Partikel-Komponenten mit `ParticlesProvider`, das einen `init`-Callback für die Engine-Einrichtung akzeptiert, und verwenden Sie dann ``, um die Partikel-Canvas zu rendern. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import { loadSlim } from "@tsparticles/slim"; + +const options = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +function App() { + return ( + { + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +`ParticlesProvider` muss ein Vorfahre jeder ``-Komponente sein. Es initialisiert die Engine einmal und stellt sie über den Kontext allen Kindern zur Verfügung. + +--- + +## Engine-Initialisierung + +Der `ParticlesProvider` akzeptiert eine `init`-Eigenschaft, die die Engine-Instanz erhält. Hier laden Sie die Funktionen, Formen, Presets oder Updater, die Ihre App benötigt. + +```tsx +// Leichtgewichtig — Kreis-Partikel, Basisbewegung, Verbindungen + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); +}}> + +// Vollständiger Funktionsumfang — alle Formen, Interaktionen, Effekte + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); +}}> + +// Preset-spezifisch — Konfetti, Feuerwerk, Schnee, Sterne + { + const { loadConfettiPreset } = await import("@tsparticles/preset-confetti"); + await loadConfettiPreset(engine); +}}> +``` + +Die Verwendung von dynamischem `import()` innerhalb des Callbacks ermöglicht Code-Splitting: Die Preset- oder Feature-Module werden nur geladen, wenn die Partikel-Komponente montiert wird. + +--- + +## Benutzerdefinierte Konfiguration + +Nachfolgend eine voll ausgestattete Konfiguration mit Interaktivität, mehreren Formtypen und einem dunklen Farbverlaufshintergrund. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, +}; + +function App() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +--- + +## Preset-Verwendung + +Das Paket `@tsparticles/configs` bietet vorgefertigte Konfigurationen, die Sie direkt an die `options`-Eigenschaft übergeben können. Kombinieren Sie sie mit dem entsprechenden Preset-Loader im `ParticlesProvider`-Init-Callback. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import configs from "@tsparticles/configs"; + +function App() { + return ( + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +Sie können `configs.confetti` durch jedes verfügbare Preset ersetzen: `configs.basic`, `configs.fireworks`, `configs.snow`, `configs.stars` usw. + +--- + +## Komponenten-Muster + +Für größere Anwendungen strukturieren Sie Ihre Partikel-Logik in einer dedizierten Komponente mit einem `particlesLoaded`-Callback für den Zugriff auf die `Container`-Instanz. + +```tsx +import { render, Component } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +class ParticlesBackground extends Component { + private container?: Container; + + handleParticlesLoaded(container?: Container) { + this.container = container; + console.log("Partikel geladen:", container?.id); + } + + render() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); + } +} + +function App() { + return ( +
+

tsParticles + Inferno

+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +## TypeScript-Beispiel + +Hier ist eine vollständige, typisierte Inferno-Anwendung mit einer responsiven Partikel-Konfiguration und Vollbild-Hintergrund. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const particlesOptions: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +function handleInit(engine: Engine): Promise { + return import("@tsparticles/slim").then(({ loadSlim }) => loadSlim(engine)); +} + +function handleParticlesLoaded(container?: Container): void { + console.log("tsParticles-Container bereit:", container?.id); +} + +function App() { + return ( + +
+

tsParticles + Inferno

+

Vollständige TypeScript-Integration

+
+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +Sie haben jetzt alles, was Sie benötigen, um tsParticles in eine Inferno-Anwendung zu integrieren. Jedes Beispiel ist in sich geschlossen und kann direkt in Ihr Projekt kopiert werden. diff --git a/websites/website/docs/de/guides/jquery.md b/websites/website/docs/de/guides/jquery.md new file mode 100644 index 00000000000..fd9c3254ad6 --- /dev/null +++ b/websites/website/docs/de/guides/jquery.md @@ -0,0 +1,274 @@ +# jQuery-Integration + +Integrieren Sie tsParticles in Ihre jQuery-basierten Projekte mit dem offiziellen jQuery-Plugin-Wrapper. + +## Installation + +### Via CDN + +Binden Sie jQuery, tsParticles und das jQuery-Plugin über Script-Tags ein: + +```html + + + +``` + +--- + +### Via npm + Build + +Installieren Sie die erforderlichen Pakete: + +```bash +npm install jquery @tsparticles/jquery tsparticles +``` + +Importieren Sie in Ihr Projekt: + +```javascript +import $ from "jquery"; +import "@tsparticles/jquery"; +``` + +## Engine-Initialisierung + +Bevor Partikel gerendert werden können, muss die tsParticles-Engine mit den benötigten Funktionen initialisiert werden. Dies geschieht über `$.particles.init`: + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); +})(); +``` + +> **Warum wird dies benötigt?** tsParticles verwendet eine modulare Architektur. `loadFull` registriert alle integrierten Formen, Interaktionen und Updater. Sie können kleinere Bundles (z. B. `tsparticles-slim`) importieren, um die Bundle-Größe zu reduzieren. + +## Grundlegende Verwendung + +Sobald die Engine initialisiert und das DOM bereit ist, wählen Sie ein Container-Element aus und rufen `.particles().load()` auf: + +```javascript +$(document).ready(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); + + $("#tsparticles") + .particles() + .load({ + background: { + color: "#0d47a1", + }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + }, + }); +}); +``` + +Das Container-Element muss im DOM vorhanden sein: + +```html +
+``` + +## Benutzerdefinierte Konfiguration + +Die `.load()`-Methode akzeptiert das vollständige `ISourceOptions`-Objekt. Hier ein umfassendes Beispiel: + +```javascript +$("#tsparticles") + .particles() + .load({ + background: { + color: "#000000", + }, + fpsLimit: 120, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + direction: "none", + enable: true, + outModes: "bounce", + speed: 4, + }, + number: { + density: { + enable: true, + }, + value: 60, + }, + opacity: { + value: 0.6, + }, + shape: { + type: ["circle", "square", "triangle"], + }, + size: { + value: { min: 2, max: 8 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + }, + interactivity: { + events: { + onClick: { + enable: true, + mode: "push", + }, + onHover: { + enable: true, + mode: "repulse", + }, + }, + modes: { + push: { + quantity: 4, + }, + repulse: { + distance: 200, + }, + }, + }, + }); +``` + +## Preset-Laden + +Wenn Sie ein Preset-Paket installiert haben (z. B. `tsparticles-preset-stars`), laden Sie es während der Engine-Initialisierung und referenzieren Sie es in der Konfiguration: + +```bash +npm install tsparticles-preset-stars +``` + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadStarsPreset } = await import("tsparticles-preset-stars"); + await loadStarsPreset(engine); + }); + + $("#tsparticles") + .particles() + .load({ + preset: "stars", + background: { color: "#0d47a1" }, + }); +})(); +``` + +## Ereignisbehandlung und Container-Steuerung + +`.particles()` gibt eine jQuery-Plugin-Instanz zurück. So greifen Sie auf den zugrunde liegenden tsParticles-`Container` zu und rufen Methoden wie `play()`, `pause()` oder `destroy()` auf: + +```javascript +const $container = $("#tsparticles"); + +// Partikel laden +$container.particles().load({ + /* Optionen */ +}); + +// Nach einigen Sekunden pausieren/fortsetzen +setTimeout(() => { + const container = $container.particles().getContainer(); + container?.pause(); +}, 5000); +``` + +## Vollständiges Beispiel + +Nachfolgend eine vollständige, in sich geschlossene HTML-Seite, die tsParticles via CDN lädt und eine Partikelszene mit interaktiven Effekten rendert: + +```html + + + + + + tsParticles + jQuery + + + +
+ + + + + + + +``` + +## API-Referenz + +| Methode | Beschreibung | +| ---------------------------------- | ------------------------------------------------------------------- | +| `$.particles.init(fn)` | Engine mit einem Loader-Callback initialisieren | +| `$(el).particles()` | Plugin-Instanz auf dem Element erstellen | +| `$(el).particles().load(opts)` | Partikel-Konfiguration laden und starten | +| `$(el).particles().destroy()` | Partikel-Instanz zerstören und aufräumen | +| `$(el).particles().getContainer()` | Zugrunde liegenden `Container` für imperative Steuerung zurückgeben | diff --git a/websites/website/docs/de/guides/lit.md b/websites/website/docs/de/guides/lit.md new file mode 100644 index 00000000000..9af3712a9f3 --- /dev/null +++ b/websites/website/docs/de/guides/lit.md @@ -0,0 +1,301 @@ +--- +title: Lit +description: Integrieren Sie tsParticles mit Lit über den offiziellen @tsparticles/lit-Webkomponenten-Wrapper. +--- + +# Lit-Integration + +Das Paket `@tsparticles/lit` bietet ein mit Lit erstelltes benutzerdefiniertes ``-Element, das es Ihnen ermöglicht, tsParticles deklarativ in jedem Lit-Projekt oder in einer einfachen HTML-Seite zu verwenden. + +## Installation + +```bash +npm install @tsparticles/lit tsparticles +``` + +Das Paket ist vollständig typisiert und enthält Lits reaktive Controller-Muster für reaktive Aktualisierungen der Partikel-Optionen. + +## Engine-Initialisierung + +Rufen Sie `initParticlesEngine` auf, bevor Sie die ``-Komponente registrieren oder in Ihre Anwendung importieren. Dies muss genau einmal geschehen. + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadFull } from "tsparticles"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +Für optimierte Bundle-Größen importieren Sie nur die Funktionen, die Ihr Projekt benötigt: + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadBasic } from "@tsparticles/basic"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +void initParticlesEngine(async (engine) => { + await loadBasic(engine); + await loadConfettiPreset(engine); +}); +``` + +## Grundlegende Verwendung + +Nach der Initialisierung der Engine verwenden Sie das ``-Element in jeder Lit-Vorlage oder HTML-Datei: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private options = { + background: { + color: "#0d1117", + }, + particles: { + number: { value: 60 }, + color: { value: "#58a6ff" }, + links: { + enable: true, + color: "#58a6ff", + }, + move: { enable: true, speed: 2 }, + }, + }; + + render() { + return html` `; + } +} +``` + +Die `.options`-Syntax (mit führendem Punkt) ist Lits Eigenschaftsbindung und stellt sicher, dass das Objekt als Referenz übergeben und nicht als Attribut serialisiert wird. + +## Einfache HTML-Verwendung + +Sobald `@tsparticles/lit` gebündelt oder geladen ist, funktioniert das Element auch in einfachem HTML: + +```html + + + + + + + + + +``` + +Sie können ein minimales Optionsobjekt als JSON-Attribut übergeben: + +```html + +``` + +## Benutzerdefinierte Konfiguration + +Übergeben Sie eine vollständige tsParticles-Konfiguration als Lit-Eigenschaft: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-particles") +class MyParticles extends LitElement { + @property({ type: Object }) + options: ISourceOptions = { + background: { + color: "#0d1117", + }, + fpsLimit: 120, + fullScreen: { + enable: true, + zIndex: -1, + }, + particles: { + color: { + value: ["#ff5733", "#33ff57", "#3357ff"], + }, + links: { + color: "#ffffff", + enable: true, + opacity: 0.3, + distance: 150, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + }, + number: { + value: 100, + density: { + enable: true, + }, + }, + opacity: { + value: 0.6, + animation: { + enable: true, + speed: 0.5, + minimumValue: 0.1, + }, + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 2, + minimumValue: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + }, + modes: { + grab: { + distance: 180, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + }; + + render() { + return html` `; + } +} +``` + +## Ereignisbehandlung + +Hören Sie auf das benutzerdefinierte `particles-loaded`-Ereignis, das vom ``-Element ausgelöst wird: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import type { Container } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private handleParticlesLoaded(e: CustomEvent) { + const container = e.detail; + console.log("Partikel geladen:", container); + container?.refresh(); + } + + render() { + return html` `; + } +} +``` + +## TypeScript-Beispiel + +Ein vollständig typisiertes Lit-Element mit `initParticlesEngine`, reaktiven Optionen und Ereignisbehandlung: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import { initParticlesEngine } from "@tsparticles/lit"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import "@tsparticles/lit"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +@customElement("particles-background") +class ParticlesBackground extends LitElement { + @property({ type: Object }) + options: ISourceOptions = {}; + + @property({ type: Boolean, attribute: "fullscreen" }) + fullscreen = true; + + protected onParticlesLoaded(e: CustomEvent) { + console.log("Container bereit:", e.detail.id); + } + + render() { + return html` + + + `; + } +} +``` + +## Dynamische Aktualisierungen + +Da `` Lits reaktive Eigenschaften verwendet, führt eine Änderung der `options`-Eigenschaft automatisch zu einer Aktualisierung der Partikel: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("dynamic-particles") +class DynamicParticles extends LitElement { + @state() + private theme: "light" | "dark" = "dark"; + + private get options(): ISourceOptions { + return this.theme === "dark" + ? { + background: { color: "#0d1117" }, + particles: { color: { value: "#58a6ff" } }, + } + : { + background: { color: "#ffffff" }, + particles: { color: { value: "#0969da" } }, + }; + } + + private toggleTheme() { + this.theme = this.theme === "dark" ? "light" : "dark"; + } + + render() { + return html` + + + `; + } +} +``` + +Die Komponente überwacht die `options`-Eigenschaft und ruft intern `refresh()` auf, sobald sie sich ändert, wodurch die Partikel-Konfiguration zur Laufzeit nahtlos aktualisiert wird. diff --git a/websites/website/docs/de/guides/nextjs.md b/websites/website/docs/de/guides/nextjs.md new file mode 100644 index 00000000000..6e314e3edd5 --- /dev/null +++ b/websites/website/docs/de/guides/nextjs.md @@ -0,0 +1,492 @@ +--- +title: Next.js-Integration +description: Schritt-für-Schritt-Anleitung zur Integration von tsParticles in eine Next.js-Anwendung mit dem App Router. +--- + +# Next.js-Integration + +Diese Anleitung behandelt die Integration von tsParticles in ein Next.js-Projekt mit dem **App Router** (Next.js 13+). Für den legacy Pages Router siehe den Abschnitt [Legacy Pages Router](#legacy-pages-router) am Ende. + +## Installation + +Installieren Sie den `@tsparticles/react`-Wrapper und die vollständige `tsparticles`-Engine (oder ein Slim-Bundle für kleinere Builds): + +```bash +npm install @tsparticles/react tsparticles +``` + +Wenn Sie das kleinere `@tsparticles/slim`-Bundle bevorzugen: + +```bash +npm install @tsparticles/react @tsparticles/slim +``` + +## Grundlegende Verwendung (App Router) + +Next.js-App-Router-Komponenten sind standardmäßig serverseitig. Da tsParticles die Browser-`canvas`-API benötigt, müssen Sie die Komponente mit der `"use client"`-Direktive kennzeichnen. + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesBackground() { + const particlesLoaded = useCallback((container?: Container) => { + console.log("Partikel geladen", container); + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }), + [], + ); + + return ; +} +``` + +Erstellen Sie dies als `components/particles-background.tsx` und importieren Sie es in eine beliebige Seite oder ein Layout. Da die Datei mit `"use client"` beginnt, wird sie auf dem Client gerendert – genau dort, wo tsParticles sein muss. + +## Themenwechsel + +Kombinieren Sie tsParticles mit Next.js-Theme-Umschaltern, indem Sie die Optionen aus dem aktuellen Theme-Status ableiten: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useMemo, useState, useCallback } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ThemeAwareParticles() { + const [theme, setTheme] = useState<"light" | "dark">("dark"); + + const toggleTheme = useCallback(() => { + setTheme((t) => (t === "dark" ? "light" : "dark")); + }, []); + + const particlesLoaded = useCallback((_container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { + color: theme === "dark" ? "#000000" : "#ffffff", + }, + particles: { + color: { value: theme === "dark" ? "#ffffff" : "#000000" }, + number: { value: 100 }, + links: { + enable: true, + color: theme === "dark" ? "#ffffff" : "#000000", + }, + move: { enable: true }, + }, + }), + [theme], + ); + + return ( + <> + + + + ); +} +``` + +Das `options`-Objekt wird über `useMemo` immer dann neu erstellt, wenn sich `theme` ändert, sodass die Canvas automatisch aktualisiert wird. + +## Konfetti-Effekt + +Verwenden Sie `@tsparticles/preset-confetti`, um bei Ereignissen wie Button-Klicks festliches Konfetti auszulösen: + +```bash +npm install @tsparticles/preset-confetti +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Container, ISourceOptions, Engine } from "@tsparticles/engine"; + +export default function ConfettiButton() { + const [active, setActive] = useState(false); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadConfettiPreset(engine); + }, []); + + const particlesLoaded = useCallback( + async (container?: Container) => { + if (active && container) { + await container.play(); + } + }, + [active], + ); + + const options: ISourceOptions = useMemo( + () => ({ + preset: "confetti", + fullScreen: { zIndex: 1000 }, + }), + [], + ); + + const handleCelebrate = useCallback(() => { + setActive(true); + setTimeout(() => setActive(false), 5000); + }, []); + + return ( + <> + {active && } + + + ); +} +``` + +Der `init`-Callback lädt das Konfetti-Preset in die Engine, bevor die Partikel erstellt werden. + +## Feuerwerks-Effekt + +Ähnlich erzeugt das Feuerwerk-Preset ein spektakuläres Feuerwerk: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; +import type { Container, Engine } from "@tsparticles/engine"; + +export default function FireworksBackground() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFireworksPreset(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options = useMemo( + () => ({ + preset: "fireworks" as const, + fullScreen: { zIndex: -1 }, + background: { + color: "#000", + }, + }), + [], + ); + + return ; +} +``` + +## Vollständiges TypeScript-Beispiel mit Container-Ref + +Greifen Sie auf die `Container`-Instanz zu, um die Animation programmatisch zu steuern (abspielen, pausieren, zerstören, Bild exportieren): + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +export default function ControllableParticles() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFull(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + fpsLimit: 120, + interactivity: { + events: { + onClick: { enable: true, mode: "push" }, + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + push: { quantity: 4 }, + repulse: { distance: 100 }, + }, + }, + particles: { + color: { value: "#ff0000" }, + links: { + enable: true, + color: "#ff0000", + distance: 150, + }, + move: { enable: true, speed: 2 }, + number: { value: 60 }, + size: { value: { min: 1, max: 5 } }, + }, + }), + [], + ); + + const handlePause = useCallback(() => { + containerRef.current?.pause(); + }, []); + + const handlePlay = useCallback(() => { + containerRef.current?.play(); + }, []); + + return ( +
+ +
+ + +
+
+ ); +} +``` + +Wichtige Punkte: + +- `particlesInit` lädt die Engine-Funktionen (wird nur einmal pro Komponenten-Mount ausgeführt). +- `particlesLoaded` feuert jedes Mal, wenn der Container vollständig initialisiert ist. +- `containerRef` hält die `Container`-Instanz, damit Sie später ihre Methoden aufrufen können. + +## Performance: useMemo und useCallback + +Umwickeln Sie statische oder selten ändernde Optionen immer mit `useMemo` und Ereignis-Handler mit `useCallback`, um unnötige Neu-Renderings der Canvas zu verhindern: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function PerformanceExample() { + const [particlesCount, setParticlesCount] = useState(80); + + // Stabiler Callback — wird nie neu erstellt, außer bei Abhängigkeitsänderungen + const particlesLoaded = useCallback((container?: Container) => { + console.log("Container bereit", container?.id); + }, []); + + // Stabiles Optionsobjekt — verhindert Canvas-Neuinitialisierung + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: particlesCount }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [particlesCount], + ); + + return ( +
+ + +
+ ); +} +``` + +Ohne diese Optimierungen würde jedes erneute Rendern des Elternteils ein neues `options`-Objekt erstellen, was zur Neu erstellung der Canvas führen würde. + +## Seitenintegration + +Fügen Sie einen Partikel-Hintergrund zu einem Seiten-Layout hinzu, ohne den Seiteninhalt zu beeinträchtigen: + +```tsx +// app/layout.tsx (Server-Komponente) +import dynamic from "next/dynamic"; + +const ParticlesBackground = dynamic(() => import("@/components/particles-background"), { ssr: false }); + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + +
{children}
+ + + ); +} +``` + +Verwenden Sie `dynamic()` mit `ssr: false`, um sicherzustellen, dass die Komponente niemals während des serverseitigen Renderings ausgeführt wird. Die Partikel-Canvas sitzt über CSS `z-index` hinter dem Hauptinhalt. + +## Mehrere Instanzen + +Sie können mehrere unabhängige `Particles`-Komponenten auf derselben Seite rendern, jede mit eigener Konfiguration: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +function ParticlesGallery() { + const loaded = useCallback((c?: Container) => {}, []); + + const redOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#1a0000" }, + particles: { + color: { value: "#ff0000" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + const blueOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#00001a" }, + particles: { + color: { value: "#0000ff" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + return ( +
+ + +
+ ); +} +``` + +Jede `Particles`-Komponente erstellt eine unabhängige Canvas mit eigener Animationsschleife. Setzen Sie `fullScreen: false` und geben Sie jeder eine feste Höhe, damit sie im Dokumentenfluss koexistieren. + +## Legacy Pages Router + +Wenn Sie den Next.js **Pages Router** (`pages/`-Verzeichnis) verwenden, ist der Ansatz ähnlich, jedoch ohne die `"use client"`-Direktive. Stattdessen können Sie einen dynamischen Import in der Seitenkomponente verwenden: + +```tsx +// pages/index.tsx +import dynamic from "next/dynamic"; +import type { NextPage } from "next"; + +const ParticlesComponent = dynamic(() => import("../components/particles-component"), { ssr: false }); + +const Home: NextPage = () => { + return ( +
+ +

Willkommen

+
+ ); +}; + +export default Home; +``` + +Die Komponente selbst (`components/particles-component.tsx`) ist eine einfache React-Komponente: + +```tsx +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesComponent() { + const particlesLoaded = useCallback((container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 80 }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [], + ); + + return ; +} +``` + +Beachten Sie, dass der Pages Router **nicht** `"use client"` erfordert, da Seitenkomponenten standardmäßig bereits clientseitig gerendert werden. + +## Fehlerbehebung + +| Symptom | Ursache | Lösung | +| ------------------------------ | ---------------------------------------- | ----------------------------------------------------------------------------------------------- | +| Leere weiße Seite | SSR rendert eine Canvas-abhängiges Modul | Verwenden Sie `dynamic(..., { ssr: false })` oder umschließen Sie es in einer Client-Komponente | +| Canvas wird nicht angezeigt | Container hat keine Höhe | Setzen Sie `fullScreen: { zIndex: -1 }` oder geben Sie explizite Maße an | +| Optionsänderung nicht sichtbar | Keine neue Objektreferenz erstellt | Verwenden Sie `useMemo` mit korrektem Abhängigkeitsarray | +| Preset funktioniert nicht | Preset vor Container-Init nicht geladen | Rufen Sie `loadXPreset(engine)` innerhalb des `init`-Callbacks auf | + +## Nächste Schritte + +- Durchstöbern Sie die [Interaktiven Demos](/demos/) für fertige Konfigurationen. +- Lesen Sie die vollständige [Optionen-Referenz](/options/) für jeden verfügbaren Parameter. +- Besuchen Sie die [Presets-Seite](/demos/presets) für weitere vorgefertigte Presets wie Schnee, Sterne und Glühwürmchen. diff --git a/websites/website/docs/de/guides/nuxt.md b/websites/website/docs/de/guides/nuxt.md new file mode 100644 index 00000000000..c160da72b7f --- /dev/null +++ b/websites/website/docs/de/guides/nuxt.md @@ -0,0 +1,463 @@ +--- +title: Nuxt-Integration +description: Schritt-für-Schritt-Anleitung zur Integration von tsParticles in eine Nuxt 3 / Nuxt 4 Anwendung. +--- + +# Nuxt-Integration + +Diese Anleitung behandelt die Integration von tsParticles in ein **Nuxt 3** (und Nuxt 4) Projekt mit dem offiziellen `@tsparticles/vue3`-Wrapper. Nuxt läuft sowohl server- als auch clientseitig, daher müssen Sie Partikel-Komponenten gegen SSR absichern. + +## Installation + +Installieren Sie den Vue 3 Wrapper und das Engine-Bundle Ihrer Wahl: + +```bash +npm install @tsparticles/vue3 tsparticles +``` + +Für ein kleineres Bundle installieren Sie `@tsparticles/slim` anstelle von `tsparticles`: + +```bash +npm install @tsparticles/vue3 @tsparticles/slim +``` + +## Grundlegende Verwendung + +Nuxt rendert Komponenten standardmäßig auf dem Server. Da tsParticles die Browser-`canvas`-API benötigt, müssen Sie die ``-Komponente in einen ``-Tag einwickeln: + +```vue + + + + + +``` + +Der ``-Wrapper stellt sicher, dass die ``-Komponente nur im Browser montiert wird, was Hydrierungskonflikte verhindert. + +## Konfiguration + +Verwenden Sie den vollständigen `ISourceOptions`-Typ für eine typsichere Konfiguration. Sie können Ihre Optionen inline definieren oder aus einer separaten Konfigurationsdatei importieren: + +```vue + +``` + +## Schnee-Effekt + +Erstellen Sie einen winterlichen Schneefall-Effekt mit dem Schnee-Preset: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +Da das Preset mit einem `await` auf oberster Ebene im ` +``` + +Verfügbare Interaktionsmodi sind: `grab`, `bubble`, `connect`, `repulse`, `push`, `remove`, `attract` und `slow`. + +## Ereignisbehandlung + +Die ``-Komponente sendet mehrere Lebenszyklus-Ereignisse: + +```vue + + + +``` + +| Ereignis | Payload | Beschreibung | +| -------------------- | ----------- | ------------------------------------------------------------------------------- | +| `@particles-init` | `Engine` | Wird einmal ausgelöst, wenn die tsParticles-Engine initialisiert wird | +| `@particles-loaded` | `Container` | Wird jedes Mal ausgelöst, wenn der Container das Laden oder Neuladen abschließt | +| `@particles-destroy` | keins | Wird ausgelöst, wenn der Container zerstört wird | + +## Vollständiges TypeScript-Beispiel + +Eine vollständige, typisierte Komponente mit expliziten Importen und Lebenszyklus-Bewusstsein: + +```vue + + + + + +``` + +## Seitenintegration + +Fügen Sie einen Partikel-Hintergrund zu einer bestimmten Nuxt-Seite hinzu, indem Sie die Komponente im Seiten-Template platzieren: + +```vue + + + + + +``` + +Wenn Sie Partikel auf **jeder** Seite wünschen, fügen Sie die Komponente zu `layouts/default.vue` anstelle einzelner Seiten hinzu. + +## Nuxt 4 Hinweise + +Nuxt 4 behält die Abwärtskompatibilität mit Nuxt 3s ``- und ` +``` + +## Fehlerbehebung + +| Symptom | Ursache | Lösung | +| ------------------------------------------ | ------------------------------------------ | --------------------------------------------------------------------- | +| Leerer Bildschirm / Hydrierungsfehler | `` auf dem Server gerendert | In `` einwickeln | +| Preset hat keine Wirkung | Preset vor Komponenten-Mount nicht geladen | Rufen Sie `loadXPreset()` mit top-level await im ` + +``` + +Die Engine initialisiert einmal und wird von allen ``-Instanzen in Ihrer App gemeinsam genutzt. + +--- + +## Grundlegende Verwendung + +Nach der Initialisierung der Engine verwenden Sie die ``-Komponente in Ihrer Vorlage. Übergeben Sie die Konfiguration als JSON-stringifiziertes Optionsobjekt oder als Referenz auf eine Eigenschaft Ihrer Komponente. + +```html + + + + + +``` + +--- + +## Bedingtes Rendern + +Verwenden Sie Riot's `if={}`-Direktive mit einer Zustandseigenschaft, um das Rendern der Partikel-Komponente zu verzögern, bis die Engine initialisiert ist. Dies vermeidet Layout-Verschiebungen und stellt sicher, dass die Komponente eine bereite Engine erhält. + +```html + + + + + +``` + +Der Aufruf von `this.update()` löst ein erneutes Rendern aus, sodass das ``-Tag erscheint, sobald das Promise aufgelöst wird. + +--- + +## Preset-Verwendung + +Das Paket `@tsparticles/configs` bietet vorgefertigte Konfigurationen für gängige Effekte wie Konfetti, Feuerwerk, Schnee und Sterne. Verwenden Sie sie direkt als Ihr Optionsobjekt. + +```html + + + + + +``` + +Verfügbare Presets umfassen `basic`, `confetti`, `fireworks`, `snow`, `stars` und mehr. Jedes Preset erfordert, dass das entsprechende Preset-Paket im Engine-Callback geladen wird. Zum Beispiel erfordert `configs.fireworks` `loadFireworksPreset`. + +--- + +## Benutzerdefinierte Konfiguration + +Erstellen Sie eine benutzerdefinierte Konfiguration mit Interaktivität, mehreren Formen und erweiterten Animationsoptionen. + +```html + + + + + +``` + +--- + +## Vollständige Komponente + +Nachfolgend eine vollständige `.riot`-Datei, die alles zusammenführt: Engine-Initialisierung in `onBeforeMount`, bedingtes Rendern mit Zustand, eine umfangreiche Konfiguration mit Interaktivität und einen `particlesLoaded`-Callback über die integrierte Unterstützung für geladene Ereignisse der Komponente. + +```html + +
+

tsParticles + Riot.js

+ + {#if state.particlesInitialized} + + {:else} +

Lade Partikel-Engine...

+ {/if} +
+ + + + +
+``` + +--- + +Sie haben jetzt alles, was Sie benötigen, um tsParticles in eine Riot.js-Anwendung zu integrieren. Jedes Beispiel ist in sich geschlossen und kann direkt in Ihr Projekt kopiert werden. diff --git a/websites/website/docs/de/guides/solid.md b/websites/website/docs/de/guides/solid.md new file mode 100644 index 00000000000..04cf890f31f --- /dev/null +++ b/websites/website/docs/de/guides/solid.md @@ -0,0 +1,512 @@ +--- +title: SolidJS-Integration +description: Schritt-für-Schritt-Anleitung zur Integration von tsParticles in eine SolidJS-Anwendung mit dem offiziellen @tsparticles/solid-Wrapper. +--- + +# SolidJS-Integration + +Diese Anleitung behandelt die Integration von tsParticles in ein **SolidJS**-Projekt mit dem offiziellen `@tsparticles/solid`-Wrapper. SolidJS' feinkörniges Reaktivitätsmodell arbeitet gut mit tsParticles zusammen – Optionsänderungen lösen gezielte Canvas-Aktualisierungen ohne vollständige Neuinitialisierung aus. + +## Installation + +Installieren Sie den SolidJS-Wrapper und das Engine-Bundle Ihrer Wahl: + +```bash +npm install @tsparticles/solid tsparticles +``` + +Für ein kleineres Bundle verwenden Sie `@tsparticles/slim` stattdessen: + +```bash +npm install @tsparticles/solid @tsparticles/slim +``` + +## Grundlegende Verwendung + +SolidJS läuft vollständig im Browser (kein SSR), daher müssen Sie nicht gegen Server-Rendering absichern. Die Engine muss jedoch asynchron initialisiert werden, bevor Partikel gerendert werden. + +Verwenden Sie `initParticlesEngine` innerhalb von `onMount`, um die Engine-Funktionen zu laden, und rendern Sie dann die ``-Komponente bedingt mit ``: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [initialized, setInitialized] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setInitialized(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +Die ``-Komponente stellt sicher, dass das ``-Element erst in das DOM eingefügt wird, nachdem die Engine bereit ist. + +## Engine-Initialisierung + +Die Funktion `initParticlesEngine` akzeptiert einen Callback, der die `Engine`-Instanz erhält. Verwenden Sie diesen Callback, um die Funktionen zu registrieren, die Ihre Konfiguration benötigt: + +```tsx +import { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import { loadSlim } from "@tsparticles/slim"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Engine } from "@tsparticles/engine"; + +// Minimal — nur Basisformen und Bewegungen +initParticlesEngine((engine: Engine) => loadSlim(engine)).then(() => { + console.log("Engine bereit (slim)"); +}); + +// Vollständig — alle Funktionen enthalten +initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => { + console.log("Engine bereit (full)"); +}); + +// Nur Preset — nur die Funktionen, die für ein bestimmtes Preset benötigt werden +initParticlesEngine((engine: Engine) => loadConfettiPreset(engine)).then(() => { + console.log("Konfetti-Preset geladen"); +}); +``` + +Rufen Sie `initParticlesEngine` einmal in Ihrer App auf — typischerweise im `onMount` der Root-Komponente. Die Engine-Instanz wird zwischengespeichert, sodass nachfolgende Aufrufe sofort zurückkehren. + +## Bedingtes Rendern + +Verwenden Sie SolidJS' ``-Kontrollfluss, um das Rendern zu verzögern, bis die Engine initialisiert ist: + +```tsx +import { createSignal, Show, onMount } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import type { Engine } from "@tsparticles/engine"; +import type { Component } from "solid-js"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + Lade Partikel...

}> + +
+ ); +}; +``` + +Die `fallback`-Eigenschaft zeigt einen Ladeindikator an, während die Engine initialisiert wird. + +## Preset-Verwendung + +Verwenden Sie `@tsparticles/configs` für schnelle, vorgefertigte Konfigurationen: + +```bash +npm install @tsparticles/configs +``` + +```tsx +import configs from "@tsparticles/configs"; +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + +
+ + +
+
+ ); +}; + +export default App; +``` + +Verfügbare Konfigurationen umfassen: `basic`, `bubbles`, `snow`, `stars`, `fireworks`, `confetti`, `links` und mehr. + +## Interaktive Partikel + +Fügen Sie Klick- und Hover-Interaktionen durch Konfiguration des `interactivity`-Abschnitts hinzu: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 60 }, + links: { enable: true, distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 4 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +- **Hover-Modi**: `grab`, `bubble`, `repulse`, `attract`, `slow`, `connect` +- **Klick-Modi**: `push`, `remove`, `repulse`, `bubble`, `attract`, `pause` + +## Benutzerdefinierte Konfiguration + +Eine vollständige benutzerdefinierte Konfiguration mit mehreren Partikelformen, Farbpaletten und Bewegungseinstellungen: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0a0a23" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { enable: true, rotateX: 600, rotateY: 1200 }, + }, + number: { + value: 40, + density: { enable: true }, + }, + opacity: { + value: { min: 0.3, max: 0.8 }, + animation: { + enable: true, + speed: 0.5, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + animation: { + enable: true, + speed: 2, + sync: false, + }, + }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.3, + width: 1, + }, + shape: { + type: ["circle", "square", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + twinkle: { + particles: { + enable: true, + frequency: 0.05, + opacity: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "bubble" }, + }, + modes: { + repulse: { distance: 120 }, + bubble: { distance: 200, size: 10, opacity: 0.8 }, + }, + }, + detectRetina: true, + }; + + return ( + + + + ); +}; + +export default App; +``` + +## Vollständiges TypeScript-Beispiel + +Eine vollständig typisierte Komponente mit Container-Referenz, Engine-Initialisierung und manuellen Steuerelementen: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [container, setContainer] = createSignal(undefined); + const [paused, setPaused] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#1a1a2e" }, + particles: { + color: { value: "#e94560" }, + number: { value: 80 }, + links: { enable: true, color: "#e94560", distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 5 } }, + }, + }; + + const particlesLoaded = (c: Container) => { + setContainer(c); + }; + + const togglePause = () => { + const c = container(); + if (c) { + if (paused()) { + c.play(); + } else { + c.pause(); + } + setPaused(!paused()); + } + }; + + return ( + + + + + ); +}; + +export default App; +``` + +## Dynamische Optionen mit Signalen + +Eine der Stärken von SolidJS ist die feinkörnige Reaktivität – Sie können Signale verwenden, um Partikel-Optionen zu steuern, und die Canvas wird effizient aktualisiert: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [color, setColor] = createSignal("#ff0000"); + const [particleCount, setParticleCount] = createSignal(60); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + // Optionen sind ein reguläres Objekt – es wird reaktiv durch + // das interne Tracking der Particle-Komponente gelesen + const options = (): ISourceOptions => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#000" }, + particles: { + color: { value: color() }, + number: { value: particleCount() }, + links: { enable: true, color: color() }, + move: { enable: true }, + }, + }); + + return ( + + {}} /> +
+ + +
+
+ ); +}; + +export default App; +``` + +Da `options` eine Funktion ist, die auf Signale zugreift, erhält die ``-Komponente jedes Mal, wenn sich `color()` oder `particleCount()` ändert, ein neues Optionsobjekt und wendet nur die geänderten Eigenschaften auf die vorhandene Canvas an. + +## Preset mit benutzerdefinierten Überschreibungen + +Laden Sie ein Preset und führen Sie dann benutzerdefinierte Überschreibungen für einen maßgeschneiderten Effekt zusammen: + +```tsx +import { loadSnowPreset } from "@tsparticles/preset-snow"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadSnowPreset(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + preset: "snow", + fullScreen: { zIndex: -1 }, + background: { color: "#0d0d2b" }, + particles: { + // Überschreiben der Schneefarbe auf Blau + color: { value: "#88ccff" }, + // Erhöhen der Anzahl der Flocken + number: { value: 300 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +Das Preset liefert Standardwerte für jede Option, und Ihre Überschreibungen werden darauf angewendet – Sie müssen nur die Eigenschaften angeben, die Sie ändern möchten. + +## Fehlerbehebung + +| Symptom | Ursache | Lösung | +| ------------------------------ | -------------------------------------------- | -------------------------------------------------------------------------------------------- | +| Leeres DOM-Element | Engine vor dem Rendern nicht initialisiert | Wickeln Sie `` in `` | +| Keine Partikel sichtbar | Fehlendes `move.enable` oder `number.value` | Stellen Sie `particles.move.enable: true` und `particles.number.value > 0` sicher | +| Canvas hinter Inhalt | Fehlendes `zIndex` in fullScreen | Verwenden Sie `fullScreen: { zIndex: -1 }` | +| Optionsänderung nicht sichtbar | Objektreferenz ändert sich nicht | Wickeln Sie Optionen in eine Funktion oder einen Store; vermeiden Sie statische Objekte | +| Engine nicht gefunden | Fehlender `loadFull`- oder `loadSlim`-Import | Installieren Sie `tsparticles` oder `@tsparticles/slim` und rufen Sie `loadFull(engine)` auf | + +## Nächste Schritte + +- Erkunden Sie den [Configs-Playground](/playground/configs) für sofort einsatzbereite Konfigurationen. +- Lesen Sie die [Optionen-Referenz](/options/) für die vollständige Liste der Parameter. +- Durchstöbern Sie den [SolidJS-Quellcode](https://github.com/tsparticles/solid) auf GitHub für Wrapper-Interna. diff --git a/websites/website/docs/de/guides/stencil.md b/websites/website/docs/de/guides/stencil.md new file mode 100644 index 00000000000..04fcb371530 --- /dev/null +++ b/websites/website/docs/de/guides/stencil.md @@ -0,0 +1,359 @@ +--- +title: Stencil-Anleitung +description: Vollständige Anleitung zur Integration von tsParticles mit Stencil-Komponenten. +--- + +# Stencil-Anleitung + +## Inhaltsverzeichnis + +1. [Installation](#installation) +2. [Custom Elements Registrierung](#custom-elements-registration) +3. [Grundlegende Verwendung](#basic-usage) +4. [Engine-Initialisierung](#engine-initialization) +5. [Benutzerdefinierte Konfiguration](#custom-configuration) +6. [Komponenten-Lebenszyklus](#component-lifecycle) +7. [TypeScript-Beispiel](#typescript-example) + +--- + +## Installation + +Installieren Sie den Stencil-Wrapper und die tsParticles-Engine über npm: + +```bash +npm install @tsparticles/stencil tsparticles +``` + +Optional ein Preset-Bundle installieren, um die manuelle Konfiguration zu reduzieren: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Custom Elements Registrierung + +Das Paket `@tsparticles/stencil` bietet eine `defineCustomElements`-Funktion, die das benutzerdefinierte ``-Element beim Browser registriert. Rufen Sie sie einmal auf, bevor Sie die Komponente irgendwo in Ihrer App verwenden. + +```tsx +import { defineCustomElements } from "@tsparticles/stencil/loader"; + +// Registrieren des -Elements +defineCustomElements(); +``` + +Für Stencil-Projekte, die Lazy-Loading verwenden, rufen Sie dies innerhalb von `componentWillLoad` oder in der Root-Komponente Ihrer App auf, um sicherzustellen, dass das Element vor dem Rendern verfügbar ist. + +--- + +## Grundlegende Verwendung + +Sobald das benutzerdefinierte Element registriert ist, können Sie `` in Ihrem JSX mit einer `options`-Eigenschaft und einem `init`-Callback verwenden, um die erforderlichen Engine-Funktionen zu laden. + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +@Component({ tag: "my-particles" }) +export class MyParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## Engine-Initialisierung + +Die `init`-Eigenschaft empfängt die Engine-Instanz und ermöglicht es Ihnen, die benötigten Funktionen zu laden. Dies ist der empfohlene Ort, um `loadSlim`, `loadFull` oder einzelne Updater-/Interaktions-Plugins aufzurufen. + +```tsx +import { loadSlim } from "@tsparticles/slim"; +import { loadFull } from "tsparticles"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// Option A: leichtgewichtig (Kreise, Basisbewegung, Verbindungen) +init={async engine => { await loadSlim(engine); }} + +// Option B: vollständiger Funktionsumfang (alle Formen, Effekte, Presets) +init={async engine => { await loadFull(engine); }} + +// Option C: Presets (Konfetti, Feuerwerk, Schnee, Sterne) +init={async engine => { await loadConfettiPreset(engine); }} +``` + +Die Engine-Instanz ist auch nach der Initialisierung über das `container-id`-Attribut zugänglich, sodass Sie das Partikelsystem später bei Bedarf programmatisch steuern können. + +--- + +## Benutzerdefinierte Konfiguration + +Nachfolgend eine vollständige Konfiguration mit Interaktivität, mehreren Formtypen und Hover-/Klick-Modi. + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const fullOptions: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { + color: "#0f0f23", + }, +}; + +@Component({ tag: "app-particles" }) +export class AppParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## Komponenten-Lebenszyklus + +In Stencil ist der empfohlene Lebenszyklus-Hook für die einmalige Einrichtung `componentWillLoad`. Verwenden Sie ihn, um benutzerdefinierte Elemente zu registrieren und den Initialisierungsstatus zu verwalten, sodass die ``-Komponente nur rendert, wenn die Engine vorbereitet ist. + +```tsx +import { Component, h, State } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ tag: "app-root" }) +export class AppRoot { + @State() private engineReady = false; + + private options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { + enable: true, + speed: 1, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#1a1a2e" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.engineReady = true; + } + + render() { + return ( +
+

tsParticles + Stencil

+ {this.engineReady && ( + { + await loadSlim(engine); + }} + /> + )} +
+ ); + } +} +``` + +Die Verwendung von `@State()` stellt sicher, dass die Komponente neu gerendert wird, wenn die Engine bereit ist, und das bedingte Rendern verhindert, dass der Partikel-Container montiert wird, bevor das benutzerdefinierte Element definiert ist. + +--- + +## TypeScript-Beispiel + +Hier ist eine vollständige, typisierte Stencil-Anwendungskomponente, die tsParticles mit dem Slim-Preset, Hover-Interaktivität und einem benutzerdefinierten dunklen Thema integriert. + +```tsx +import { Component, h, State, Prop } from "@stencil/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ + tag: "app-home", + styleUrl: "app-home.css", + shadow: true, +}) +export class AppHome { + @State() private initialized = false; + + @Prop() readonly title: string = "Willkommen"; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.initialized = true; + } + + private handleInit = async (engine: Engine): Promise => { + await loadSlim(engine); + }; + + private handleLoaded = async (container?: Container): Promise => { + this.container = container; + console.log("Partikel-Container geladen:", container?.id); + }; + + render() { + return ( +
+

{this.title}

+

Unterstützt von tsParticles und Stencil

+ + {this.initialized && ( + + )} +
+ ); + } +} +``` + +Das `particlesLoaded`-Ereignis wird ausgelöst, sobald der erste Frame gerendert ist, und gibt Ihnen Zugriff auf die `Container`-Instanz für programmatische Steuerung (Abspielen, Pausieren, Stoppen, Themes wechseln). + +--- + +Sie haben jetzt alles, was Sie benötigen, um tsParticles in eine Stencil-Anwendung zu integrieren. Jedes Beispiel ist in sich geschlossen und kann direkt in Ihr Projekt kopiert werden. diff --git a/websites/website/docs/de/guides/svelte.md b/websites/website/docs/de/guides/svelte.md new file mode 100644 index 00000000000..40883ad6612 --- /dev/null +++ b/websites/website/docs/de/guides/svelte.md @@ -0,0 +1,580 @@ +--- +title: Svelte-Integration +description: Schritt-für-Schritt-Anleitung zur Integration von tsParticles in Svelte- und SvelteKit-Anwendungen mit @tsparticles/svelte. +--- + +# Svelte-Integration + +Das Paket `@tsparticles/svelte` bietet eine native Svelte-Komponente für tsParticles. Diese Anleitung behandelt Svelte (mit Vite) und SvelteKit, einschließlich reaktiver Optionen, Ereignisbehandlung und mehrerer Instanzen. + +--- + +## Installation + +```bash +npm install @tsparticles/svelte @tsparticles/engine +``` + +Für das vollständige Bundle oder Presets: + +```bash +npm install tsparticles +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +``` + +--- + +## Grundlegende Verwendung + +```svelte + + + +``` + +--- + +## Engine-Initialisierung + +Übergeben Sie einen `on:init`-Ereignis-Handler, um die Plugins und Presets zu laden, die Ihre App benötigt: + +```svelte + + + +``` + +Alternativ können Sie das Dienstprogramm `initParticlesEngine` vor dem Mounten verwenden: + +```svelte + + +{#if ready} + +{/if} +``` + +--- + +## Schnee-Effekt + +```bash +npm install @tsparticles/preset-snow +``` + +```svelte + + + +``` + +Passen Sie das Preset-Verhalten durch Hinzufügen weiterer Optionen an: + +```svelte + +``` + +--- + +## Sterne-Effekt + +```bash +npm install @tsparticles/preset-stars +``` + +```svelte + + + +``` + +--- + +## Interaktive Partikel + +Fügen Sie Maus-Hover- und Klick-Interaktivität hinzu: + +```svelte + + + +``` + +--- + +## Ereignisbehandlung + +```svelte + + +
+ + + +
+ + +``` + +| Ereignis | Detail | Wird ausgelöst | +| -------------------- | ----------- | -------------------------------------------- | +| `on:init` | `Engine` | Nachdem die Engine initialisiert wurde | +| `on:particlesLoaded` | `Container` | Nachdem der Container vollständig bereit ist | + +--- + +## TypeScript-Beispiel + +Vollständig typisierte Komponente: + +```svelte + + + +``` + +--- + +## Dynamische Optionen + +Reaktive Optionen aktualisieren die Partikel, ohne die Instanz neu zu erstellen: + +```svelte + + +
+ +
+ + +``` + +Die `$:`-Reaktivdeklaration berechnet `options` neu, sobald sich `color` ändert, und die `Particles`-Komponente übernimmt die neue Konfiguration automatisch. + +--- + +## Mehrere Instanzen + +Rendern Sie mehrere unabhängige Partikelsysteme auf derselben Seite: + +```svelte + + +
+
+ +
+
+ +
+
+``` + +Jede ``-Komponente erhält ihre eigene `id`, Canvas und Engine-Kontext. + +--- + +## SvelteKit-Verwendung + +In SvelteKit erfordert die Canvas die Browser-Umgebung. Deaktivieren Sie SSR für die Komponente: + +```svelte + + +{#if Component} + +{/if} +``` + +Oder wickeln Sie den Import in eine Client-only-Komponente. Für SvelteKit 2+ können Sie auch die `vite-plugin-svelte` SSR-Ausschlüsse verwenden. + +--- + +## API-Referenz + +| Eigenschaft | Typ | Standard | Beschreibung | +| ----------- | ---------------- | --------------- | -------------------------------------- | +| `id` | `string` | `"tsparticles"` | Canvas-Element-ID | +| `options` | `ISourceOptions` | `{}` | Partikel-Konfigurationsobjekt | +| `url` | `string` | — | URL zu einer Remote-JSON-Konfiguration | + +| Ereignis | Detail | Beschreibung | +| -------------------- | ----------- | ------------------------------------------------------------------------------------ | +| `on:init` | `Engine` | Wird ausgelöst, wenn die Engine initialisiert wird (zum Laden von Plugins verwenden) | +| `on:particlesLoaded` | `Container` | Wird ausgelöst, wenn der Container vollständig bereit ist | + +--- + +## Fehlerbehebung + +- **Canvas nicht sichtbar** — Stellen Sie sicher, dass der übergeordnete Container explizite Abmessungen hat (`height: 100%`, `height: 100vh` oder ein fester Pixelwert). +- **`loadFull is not a function`** — Überprüfen Sie, ob `tsparticles` installiert ist und dass Sie `loadFull` von `tsparticles` importieren (nicht von `@tsparticles/engine`). +- **Reaktivität funktioniert nicht** — Stellen Sie sicher, dass `options` eine reaktive Variable ist (`$:` oder `let`, die an eine reaktive Quelle gebunden ist). Reine `const`-Werte werden nicht aktualisiert. +- **SvelteKit leerer Bildschirm** — Importieren Sie `@tsparticles/svelte` dynamisch oder verwenden Sie den `browser`-Guard, wie im SvelteKit-Abschnitt oben gezeigt. +- **TypeScript-Fehler für `event.detail`** — Verwenden Sie die Typen `CustomEvent` und `CustomEvent` für die Ereignis-Handler. diff --git a/websites/website/docs/de/guides/vanilla.md b/websites/website/docs/de/guides/vanilla.md new file mode 100644 index 00000000000..c330223767b --- /dev/null +++ b/websites/website/docs/de/guides/vanilla.md @@ -0,0 +1,889 @@ +--- +title: Vanilla JS Leitfaden +description: Vollständiger Leitfaden zur Integration von tsParticles mit reinem JavaScript. +--- + +# Vanilla JS Leitfaden + +## Inhaltsverzeichnis + +1. [Erste Schritte](#erste-schritte) +2. [Einfache Partikel](#einfache-partikel) +3. [Konfetti-Effekt](#konfetti-effekt) +4. [Feuerwerks-Effekt](#feuerwerks-effekt) +5. [Bänder-Effekt](#bänder-effekt) +6. [Schnee-Effekt](#schnee-effekt) +7. [Netzwerk / Links-Effekt](#netzwerk-links-effekt) +8. [Sterne-Effekt](#sterne-effekt) +9. [Benutzerdefinierte Konfiguration](#benutzerdefinierte-konfiguration) +10. [Mehrere Container](#mehrere-container) +11. [Dynamische Steuerung](#dynamische-steuerung) + +--- + +## Erste Schritte + +### CDN (Schnellstart) + +Fügen Sie einen `
`-Platzhalter und Script-Tags in Ihr HTML ein. Sie benötigen mindestens die Engine und ein Bundle, und Sie müssen den Loader vor `tsParticles.load()` aufrufen. + +```html + + + + + + tsParticles – Erste Schritte + + + +
+ + + + + + +``` + +### npm + +```bash +npm install @tsparticles/engine @tsparticles/slim +``` + +Dann importieren und verwenden Sie es: + +```javascript +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +(async () => { + await loadSlim(tsParticles); + + await tsParticles.load({ + id: "tsparticles", + options: { + /* ... */ + }, + }); +})(); +``` + +> **Hinweis:** `@tsparticles/engine` allein zeichnet nichts. Sie müssen ein Bundle (`@tsparticles/slim` empfohlen) oder einzelne Plugins installieren, um sichtbare Formen zu erhalten. + +--- + +## Einfache Partikel + +Eine minimale Konfiguration, die 100 Partikel mit einer Kreisform, zufälligen Farben und sanfter Bewegung rendert. In v4 werden Partikelfarben über `paint` anstelle der alten `color`-Eigenschaft gesetzt. + +```html + + + + + + Einfache Partikel + + + +
+ + + + + + +``` + +--- + +## Konfetti-Effekt + +Verwenden Sie das dedizierte `@tsparticles/confetti`-Bundle für einen festlichen Ausbruch mit einem einzigen Funktionsaufruf. + +```html + + + + + + Konfetti + + + + + + + + + +``` + +--- + +## Feuerwerks-Effekt + +Eine Feuerwerksshow mit dem dedizierten `@tsparticles/fireworks`-Bundle mit Soundeffekten. + +```html + + + + + + Feuerwerk + + + + + + + +``` + +--- + +## Bänder-Effekt + +Verwenden Sie das dedizierte `@tsparticles/ribbons`-Bundle für fließende Bandanimationen, die auf die Mausposition reagieren. + +```html + + + + + + Bänder + + + + + + + +``` + +--- + +## Schnee-Effekt + +Sanft fallende Schneeflocken mit dem `@tsparticles/configs`-Voreinstellungskatalog. + +```html + + + + + + Schnee-Effekt + + + +
+ + + + + + + +``` + +Alternativ mit dem eigenständigen Voreinstellungspaket: + +```html + + + + +``` + +--- + +## Netzwerk / Links-Effekt + +Eine klassische Visualisierung verbundener Knoten mit Mausinteraktivität. Das `@tsparticles/slim`-Bundle enthält die Links-Interaktion und den Mouse-Grab-Modus. + +```html + + + + + + Netzwerk / Links + + + +
+ + + + + + +``` + +--- + +## Sterne-Effekt + +Ein sternenklarer Nachthimmel mit dem `@tsparticles/configs`-Voreinstellungskatalog. + +```html + + + + + + Sterne-Effekt + + + +
+ + + + + + + +``` + +Alternativ mit dem eigenständigen Voreinstellungspaket: + +```html + + + + +``` + +--- + +## Benutzerdefinierte Konfiguration + +Erstellen Sie eine Konfiguration von Grund auf mit einem Farbverlaufshintergrund, interaktiven Hover-Effekten und mehreren Formtypen mit dem Slim-Bundle. + +```html + + + + + + Benutzerdefinierte Konfiguration + + + +

Benutzerdefinierte Konfiguration

+
+ + + + + + +``` + +--- + +## Mehrere Container + +Führen Sie mehrere unabhängige Partikelinstanzen auf derselben Seite aus, jede mit ihrer eigenen Konfiguration. + +```html + + + + + + Mehrere Container + + + +
+
+
+
+ + + + + + +``` + +--- + +## Dynamische Steuerung + +Programmgesteuertes Starten, Stoppen, Pausieren und Wechseln von Themes zur Laufzeit. + +```html + + + + + + Dynamische Steuerung + + + +
+
+ + + + + + +
+ + + + + + +``` + +--- + +Sie haben nun alle wichtigen Vanilla-JS-Integrationsmuster für tsParticles v4 kennengelernt. Jedes Beispiel ist eine eigenständige HTML-Datei, die Sie in Ihrem Browser öffnen können, um tsParticles in Aktion zu sehen. diff --git a/websites/website/docs/de/guides/vue3.md b/websites/website/docs/de/guides/vue3.md new file mode 100644 index 00000000000..77800e5f0ec --- /dev/null +++ b/websites/website/docs/de/guides/vue3.md @@ -0,0 +1,622 @@ +--- +title: Vue 3-Integration +description: Schritt-für-Schritt-Anleitung zur Integration von tsParticles in Vue 3-Anwendungen mit @tsparticles/vue3. +--- + +# Vue 3-Integration + +Das Paket `@tsparticles/vue3` bietet ein natives Vue 3-Komponenten- und Plugin-System für tsParticles. Diese Anleitung behandelt alles von der grundlegenden Einrichtung bis zu fortgeschrittenen Mustern wie dynamischem Theme-Wechsel und benutzerdefinierten Presets. + +--- + +## Installation + +```bash +npm install @tsparticles/vue3 @tsparticles/engine +``` + +Optional ein Preset oder das vollständige Bundle installieren: + +```bash +# Vollständiges Bundle (alle Funktionen) +npm install tsparticles + +# Spezifische Presets +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars + +# Dienstprogramm-Konfigurationen +npm install @tsparticles/configs +``` + +--- + +## Grundlegende Verwendung + +Registrieren Sie das Plugin in Ihrem App-Einstiegspunkt und verwenden Sie dann die ``-Komponente überall. + +### App-Einstieg (`main.ts`) + +```typescript +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +const app = createApp(App); + +app.use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, +}); + +app.mount("#app"); +``` + +### Komponente (`App.vue`) + +```vue + + + +``` + +--- + +## Verwendung von `particlesInit` mit der Komponente + +Wenn Sie das globale Plugin nicht verwenden möchten, übergeben Sie einen `init`-Callback direkt: + +```vue + + + +``` + +--- + +## Ereignisse + +Die Komponente sendet mehrere Lebenszyklus-Ereignisse: + +```vue + + + +``` + +--- + +## Konfetti-Effekt + +Verwenden Sie das Konfetti-Preset für Feierlichkeiten: + +```bash +npm install @tsparticles/preset-confetti +``` + +```vue + + + +``` + +Für einen einmaligen Ausbruch laden Sie das Preset und rufen dann programmatisch `tsParticles.load()` innerhalb einer Methode auf. + +--- + +## Feuerwerks-Effekt + +Das Feuerwerk-Preset erzeugt wirkungsvolle Partikelexplosionen: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```vue + + + +``` + +> **Tipp:** Das Feuerwerk-Preset ist ressourcenintensiv. Lösen Sie es bei Benutzerinteraktion (z. B. Button-Klick) aus, indem Sie ein `v-if` umschalten, das an die Komponente gebunden ist. + +--- + +## Schnee-Effekt + +Simulieren Sie fallenden Schnee mit dem Schnee-Preset: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +--- + +## Interaktive Partikel + +Fügen Sie Hover- und Klick-Interaktivitätsmodi hinzu: + +```vue + + + +``` + +Verfügbare Interaktionsmodi: `grab`, `repulse`, `bubble`, `connect`, `push`, `remove`, `trail`, `attract`, `light`. + +--- + +## Theme-Wechsel + +Wechseln Sie dynamisch zwischen Partikel-Themes zur Laufzeit durch Aktualisieren des reaktiven Optionsobjekts: + +```vue + + + +``` + +Alternativ verwenden Sie die integrierte [themes](https://particles.js.org/docs/interfaces/Options_Interfaces_IOptions.IOptions.html#themes)-Option und die `theme`-Eigenschaft am Container für eine konfigurationsloses Umschalten. + +--- + +## Benutzerdefiniertes Preset von @tsparticles/configs + +Das Paket `@tsparticles/configs` exportiert vorgefertigte Konfigurationsobjekte: + +```bash +npm install @tsparticles/configs +``` + +```vue + + + +``` + +Durchstöbern Sie die verfügbaren Konfigurationen im `@tsparticles/configs`-Paket für sofort einsatzbereite Layouts. + +--- + +## Ansätze zur Engine-Initialisierung + +Es gibt zwei Möglichkeiten, die Engine zu initialisieren: + +### 1. Globales Plugin (empfohlen) + +```typescript +// main.ts +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +createApp(App) + .use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, + }) + .mount("#app"); +``` + +Die Engine ist dann global verfügbar und alle ``-Instanzen teilen sie. + +### 2. Init auf Komponentenebene + +Übergeben Sie einen `:init`-Callback an jede ``-Instanz. Nützlich, wenn verschiedene Komponenten unterschiedliche Pluginsätze benötigen: + +```vue + +``` + +### 3. Particles Provider (Composition API) + +Verwenden Sie den Provider, um programmatisch auf die Engine zuzugreifen: + +```vue + +``` + +--- + +## Benannte Exporte + TypeScript + +Vollständiges TypeScript-Beispiel mit allen Teilen zusammen: + +```vue + + + +``` + +--- + +## API-Referenz + +| Eigenschaft | Typ | Standard | Beschreibung | +| ----------- | ----------------------------------- | --------------- | -------------------------------------- | +| `id` | `string` | `"tsparticles"` | Canvas-Element-ID | +| `options` | `ISourceOptions` | `{}` | Partikel-Konfiguration | +| `init` | `(engine: Engine) => Promise` | — | Engine-Initialisierungs-Callback | +| `url` | `string` | — | URL zum Laden einer JSON-Konfiguration | + +| Ereignis | Payload | Beschreibung | +| ------------------- | ----------- | ---------------------------------------------------------------- | +| `@particles-loaded` | `Container` | Wird ausgelöst, wenn der Container vollständig initialisiert ist | +| `@particles-init` | `Engine` | Wird ausgelöst, nachdem die Engine initialisiert wurde | + +--- + +## Fehlerbehebung + +- **Fehler: `tsparticles is not defined`** — Stellen Sie sicher, dass `tsparticles` (oder die benötigten Presets) innerhalb des `init`-Callbacks geladen werden, bevor die Komponente rendert. +- **Canvas wird nicht angezeigt** — Überprüfen Sie, ob der übergeordnete Container eine Höhe ungleich Null hat. Fügen Sie eine CSS-Regel wie `#tsparticles { height: 100vh; }` hinzu. +- **Leistungsprobleme** — Senken Sie `fpsLimit`, reduzieren Sie `particles.number.value` oder deaktivieren Sie `detectRetina` auf Geräten mit geringer Leistung. +- **SSR (Nuxt)** — Die ``-Komponente ist Client-only. Wickeln Sie sie in `` oder verwenden Sie die `client:only`-Direktive. diff --git a/websites/website/docs/de/guides/webcomponents.md b/websites/website/docs/de/guides/webcomponents.md new file mode 100644 index 00000000000..6cc9446f597 --- /dev/null +++ b/websites/website/docs/de/guides/webcomponents.md @@ -0,0 +1,359 @@ +# Web Components + +Verwenden Sie tsParticles mit nativen Web Components über das `@tsparticles/webcomponents`-Paket. Dieser Ansatz erfordert kein Framework — nur Vanilla-JavaScript und benutzerdefinierte Elemente. + +## Installation + +### Via CDN + +Binden Sie den tsParticles-Kern und das Web Components-Bundle ein: + +```html + + +``` + +### Via npm + Build + +```bash +npm install @tsparticles/webcomponents tsparticles +``` + +Dann in Ihr JavaScript-Bundle importieren: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; +``` + +## Engine-Initialisierung + +Bevor das ``-Element rendern kann, muss die Engine mit den benötigten Funktionen initialisiert werden. Rufen Sie `initParticlesEngine` mit einem Callback auf, der die gewünschten Plugins lädt: + +```javascript +import { initParticlesEngine } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +> **Warum `loadFull`?** Es registriert alle integrierten Formen (Kreis, Quadrat, Polygon, Bild usw.), Interaktionen (Hover, Klick) und Updater (Deckkraft, Größe, Farbe usw.). Für ein kleineres Bundle verwenden Sie `tsparticles-slim` oder wählen einzelne Plugins aus. + +## Definieren des benutzerdefinierten Elements + +Nach der Engine-Initialisierung registrieren Sie das ``-Element: + +```javascript +import { defineParticlesElement } from "@tsparticles/webcomponents"; + +defineParticlesElement(); +``` + +Dies registriert das `web-particles`-Tag bei der `CustomElementRegistry` des Browsers. Es ist sicher, es mehrfach aufzurufen — doppelte Registrierungen werden ignoriert. + +## Grundlegende Verwendung + +Sobald sowohl `initParticlesEngine` als auch `defineParticlesElement` ausgeführt wurden, verwenden Sie das Element direkt in HTML: + +```html + + + + + + tsParticles Web Components + + + + + + + +``` + +## Benutzerdefinierte Konfiguration + +Das ``-Element akzeptiert Konfiguration über die `options`-Eigenschaft (JavaScript-Objekt) oder über JSON im `options`-Attribut. + +### Via JavaScript-Eigenschaft + +```javascript +const el = document.querySelector("web-particles"); +el.options = { + background: { color: "#000000" }, + fpsLimit: 60, + particles: { + color: { value: ["#ff0000", "#00ff00", "#0000ff"] }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { value: 60 }, + opacity: { value: 0.6 }, + shape: { type: ["circle", "square"] }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + repulse: { distance: 200 }, + push: { quantity: 4 }, + }, + }, +}; +``` + +### Via HTML-Attribut (JSON) + +```html + +``` + +> Bei Verwendung des `options`-Attributs muss der Wert gültiges JSON sein. Für komplexe Konfigurationen wird die Eigenschaftszuweisung bevorzugt. + +## Dynamische Erstellung + +Sie können ``-Elemente vollständig in JavaScript erstellen und jederzeit zum DOM hinzufügen: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +defineParticlesElement(); + +function createParticles(container, config) { + const el = document.createElement("web-particles"); + el.id = "dynamic-particles"; + el.style.position = "absolute"; + el.style.width = "100%"; + el.style.height = "100%"; + el.style.top = "0"; + el.style.left = "0"; + el.options = config; + container.appendChild(el); + return el; +} + +// Verwendung +const particles = createParticles(document.body, { + background: { color: "#1a1a2e" }, + particles: { + number: { value: 100 }, + links: { enable: true, color: "#e94560" }, + move: { enable: true, speed: 1 }, + }, +}); +``` + +## Erweitern des benutzerdefinierten Elements + +Sie können `ParticlesElement` ableiten, um Ihr eigenes benutzerdefiniertes Element mit integrierter Konfiguration zu erstellen: + +```javascript +import { initParticlesEngine, ParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +class MyParticlesBackground extends ParticlesElement { + constructor() { + super(); + this.style.position = "fixed"; + this.style.top = "0"; + this.style.left = "0"; + this.style.width = "100%"; + this.style.height = "100%"; + this.style.zIndex = "-1"; + } + + connectedCallback() { + this.options = { + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true, speed: 2 }, + }, + }; + super.connectedCallback(); + } +} + +customElements.define("my-particles-bg", MyParticlesBackground); +``` + +Verwendung: + +```html + +``` + +## Container-Zugriff und Steuerung + +Das benutzerdefinierte Element stellt die tsParticles-`Container`-Instanz für die imperative Steuerung bereit: + +```javascript +const el = document.querySelector("web-particles"); + +// Zugriff auf den Container (verfügbar nach connectedCallback) +const container = el.container; +container?.pause(); +container?.play(); + +// Zerstören und aufräumen +el.dispose(); +``` + +## Vollständiges Beispiel + +Eine vollständige HTML-Seite mit dem Web Components-Modul und CDN-Skripten: + +```html + + + + + + tsParticles Web Components Demo + + + +
+

tsParticles + Web Components

+

Native benutzerdefinierte Elemente, kein Framework erforderlich.

+
+ + + + + + +``` + +## API-Referenz + +| Export / Eigenschaft | Typ | Beschreibung | +| ------------------------------- | ------------------------ | --------------------------------------------------------------------- | +| `initParticlesEngine(callback)` | `function` | Initialisiert die tsParticles-Engine mit Plugin-Ladern | +| `defineParticlesElement()` | `function` | Registriert das ``-Element | +| `ParticlesElement` | `class` | Basisklasse, die Sie für benutzerdefinierte Elemente erweitern können | +| `element.options` | `ISourceOptions` | Partikel-Konfigurationsobjekt abrufen/setzen | +| `element.container` | `Container \| undefined` | Nur-Lesen-Referenz auf den zugrunde liegenden `Container` | +| `element.dispose()` | `function` | Zerstört die Partikel-Instanz und gibt Ressourcen frei | diff --git a/websites/website/docs/de/guides/wordpress.md b/websites/website/docs/de/guides/wordpress.md new file mode 100644 index 00000000000..06d3bd3b670 --- /dev/null +++ b/websites/website/docs/de/guides/wordpress.md @@ -0,0 +1,314 @@ +--- +title: WordPress-Anleitung +description: Vollständige Anleitung zur Integration von tsParticles mit WordPress unter Verwendung des Plugins, Blocks, Shortcodes und Theme-Integration. +--- + +# WordPress-Anleitung + +## Inhaltsverzeichnis + +1. [Installation](#installation) +2. [Plugin-Aktivierung](#plugin-activation) +3. [Widget- und Block-Verwendung](#widget-and-block-usage) +4. [Shortcode-Verwendung](#shortcode-usage) +5. [PHP-Filter-Konfiguration](#php-filter-configuration) +6. [Benutzerdefinierte Konfiguration via Filter](#custom-configuration-via-filter) +7. [Theme-Integration](#theme-integration) + +--- + +## Installation + +Das tsParticles-WordPress-Plugin ist über das WordPress-Plugin-Verzeichnis verfügbar. Installieren Sie es direkt über Ihr WordPress-Admin-Dashboard. + +### Vom WordPress-Admin + +1. Navigieren Sie zu **Plugins → Installieren** +2. Suchen Sie nach "tsParticles" +3. Klicken Sie bei dem tsParticles-Plugin auf **Jetzt installieren** +4. Klicken Sie auf **Aktivieren** + +### Manuelle Installation + +1. Laden Sie das Plugin-ZIP vom WordPress-Plugin-Verzeichnis oder der [Releases-Seite](https://github.com/tsparticles/wordpress/releases) herunter +2. Navigieren Sie zu **Plugins → Installieren → Plugin hochladen** +3. Wählen Sie die ZIP-Datei und klicken Sie auf **Jetzt installieren** +4. Klicken Sie auf **Aktivieren** + +--- + +## Plugin-Aktivierung + +Nach der Aktivierung registriert das Plugin: + +- Einen **Gutenberg-Block** namens "tsParticles", der im Block-Inserter verfügbar ist +- Einen **Shortcode** `[tsparticles]` für die Verwendung im Classic Editor oder in benutzerdefinierten PHP-Vorlagen +- Einen **PHP-Filter** `tsparticles_options` für Entwickler, um die Konfiguration programmatisch einzuspritzen +- Frontend-Assets (JavaScript und CSS), die nur dann eingereiht werden, wenn der Block oder Shortcode auf der Seite vorhanden ist + +Nach der Aktivierung können Sie überprüfen, ob das Plugin funktioniert, indem Sie in der WordPress-Admin-Seitenleiste auf **Einstellungen → tsParticles** gehen, wo je nach Plugin-Version eine grundlegende Einstellungsseite verfügbar sein kann. + +--- + +## Widget- und Block-Verwendung + +Das tsParticles-Plugin fügt einen benutzerdefinierten Gutenberg-Block für den Block-Editor (WordPress 5.0+) hinzu. + +### Hinzufügen des Blocks + +1. Bearbeiten Sie einen beliebigen Beitrag oder eine Seite mit dem Block-Editor (Gutenberg) +2. Klicken Sie auf die **+** (Block hinzufügen)-Schaltfläche +3. Suchen Sie nach "tsParticles" oder "Particles" +4. Klicken Sie auf den **tsParticles**-Block, um ihn einzufügen + +### Block-Einstellungen + +Nach dem Einfügen bietet das Block-Inspektor-Panel (auf der rechten Seite) folgende Einstellungen: + +- **Container-ID** — eine eindeutige HTML-ID für den Partikel-Container (Standard: `tsparticles`) +- **Breite / Höhe** — explizite Abmessungen festlegen oder Vollbildmodus verwenden +- **Z-Index** — steuert die Überlagerung relativ zu anderen Inhalten +- **Konfiguration** — ein JSON-Optionsobjekt einfügen, um das Partikel-Erscheinungsbild vollständig anzupassen + +Für Theme-Seitenleisten oder Widget-Bereiche, die keine Blöcke unterstützen, verwenden Sie stattdessen den [Shortcode](#shortcode-usage)-Ansatz. + +--- + +## Shortcode-Verwendung + +Verwenden Sie den `[tsparticles]`-Shortcode im Classic Editor, in benutzerdefinierten HTML-Blöcken oder direkt in PHP-Vorlagendateien, um Partikel-Hintergründe überall auf Ihrer Website einzubetten. + +### Einfacher Shortcode + +``` +[tsparticles] +``` + +Dies rendert die Standard-Partikel-Konfiguration (einfach schwebende Kreise auf dunklem Hintergrund). + +### Shortcode mit Optionen + +Übergeben Sie JSON-Konfiguration direkt im Shortcode mit dem `options`-Attribut: + +``` +[tsparticles options='{"particles":{"number":{"value":50},"color":{"value":"#ff0000"},"shape":{"type":"circle"},"opacity":{"value":0.5},"size":{"value":{"min":1,"max":3}},"move":{"enable":true,"speed":1,"outModes":{"default":"bounce"}}},"background":{"color":"#1a1a2e"}}'] +``` + +### Shortcode in PHP-Vorlagen + +```php +// In der header.php oder footer.php Ihres Themes +echo do_shortcode('[tsparticles]'); +``` + +Oder mit benutzerdefinierten Optionen: + +```php +$options = [ + 'particles' => [ + 'number' => ['value' => 80], + 'color' => ['value' => '#00d4ff'], + 'shape' => ['type' => 'circle'], + 'links' => [ + 'enable' => true, + 'distance' => 150, + 'color' => '#00d4ff', + 'opacity' => 0.3, + ], + 'move' => [ + 'enable' => true, + 'speed' => 1.5, + 'outModes' => ['default' => 'bounce'], + ], + ], + 'background' => ['color' => '#0d1117'], +]; + +echo do_shortcode('[tsparticles options=\'' . wp_json_encode($options) . '\']'); +``` + +--- + +## PHP-Filter-Konfiguration + +Das Plugin stellt einen `tsparticles_options`-Filter bereit, mit dem Sie die Partikel-Konfiguration aus Ihrer `functions.php`-Datei des Themes oder einem benutzerdefinierten Plugin überschreiben oder erweitern können. Dies ist der empfohlene Ansatz für Entwickler, da er die Konfiguration in PHP hält und Inline-JSON vermeidet. + +### Einfacher Filter + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + $options['background'] = ['color' => '#0d1117']; + $options['particles']['number']['value'] = 100; + $options['particles']['color']['value'] = '#00d4ff'; + $options['particles']['shape']['type'] = 'circle'; + $options['particles']['opacity']['value'] = 0.6; + $options['particles']['size']['value'] = ['min' => 2, 'max' => 5]; + $options['particles']['links']['enable'] = true; + $options['particles']['links']['distance'] = 150; + $options['particles']['links']['color'] = '#00d4ff'; + $options['particles']['links']['opacity'] = 0.3; + $options['particles']['move']['enable'] = true; + $options['particles']['move']['speed'] = 1.5; + $options['particles']['move']['outModes']['default'] = 'bounce'; + return $options; +}); +``` + +Dieser Filter wird ausgeführt, bevor der Shortcode oder Block rendert, sodass jede Instanz von tsParticles auf der Seite die angepasste Konfiguration erhält. + +--- + +## Benutzerdefinierte Konfiguration via Filter + +Hier ist eine vollständige benutzerdefinierte Konfiguration, die die volle Leistungsfähigkeit des Filters demonstriert — einschließlich Interaktivität, mehreren Formtypen und Theme-Unterstützung. + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + + // Vollbild-Hintergrund + $options['fullScreen'] = [ + 'enable' => true, + 'zIndex' => -1, + ]; + + $options['fpsLimit'] = 60; + + // Partikel-Einstellungen + $options['particles'] = [ + 'number' => [ + 'value' => 60, + 'density' => ['enable' => true, 'width' => 800, 'height' => 800], + ], + 'color' => [ + 'value' => ['#ff6b6b', '#feca57', '#48dbfb', '#ff9ff3', '#54a0ff'], + ], + 'shape' => [ + 'type' => ['circle', 'triangle', 'polygon'], + 'options' => [ + 'polygon' => ['sides' => 6], + ], + ], + 'opacity' => [ + 'value' => ['min' => 0.4, 'max' => 0.8], + ], + 'size' => [ + 'value' => ['min' => 3, 'max' => 8], + ], + 'links' => [ + 'enable' => true, + 'distance' => 200, + 'color' => '#ffffff', + 'opacity' => 0.15, + 'width' => 1, + ], + 'move' => [ + 'enable' => true, + 'speed' => 2, + 'direction' => 'none', + 'random' => true, + 'straight' => false, + 'outModes' => ['default' => 'out'], + ], + ]; + + // Interaktivität + $options['interactivity'] = [ + 'events' => [ + 'onHover' => ['enable' => true, 'mode' => 'attract'], + 'onClick' => ['enable' => true, 'mode' => 'repulse'], + ], + 'modes' => [ + 'attract' => ['distance' => 200, 'duration' => 0.4, 'factor' => 1], + 'repulse' => ['distance' => 200, 'duration' => 0.4], + ], + ]; + + // Hintergrund + $options['background'] = [ + 'color' => '#0f0f23', + ]; + + // Theme-Unterstützung — Hellmodus-Umschaltung + $options['themes'] = [ + [ + 'name' => 'light', + 'default' => ['value' => false], + 'options' => [ + 'background' => ['color' => '#f0f0f5'], + 'particles' => [ + 'color' => ['value' => ['#e74c3c', '#2ecc71', '#3498db', '#f1c40f']], + 'links' => ['color' => '#333333', 'opacity' => 0.2], + ], + ], + ], + ]; + + return $options; +}); +``` + +--- + +## Theme-Integration + +Um tsParticles zu einem dauerhaften Hintergrund in Ihrem gesamten WordPress-Theme zu machen, fügen Sie den Shortcode oder einen direkten PHP-Aufruf in die `header.php` oder `footer.php` Ihres Themes ein. + +### Header-Hintergrund + +```php + + +
+ +
+ +``` + +### Vollbild-Hintergrund-Styles + +Fügen Sie das folgende CSS zu Ihrer `style.css` des Themes oder via `wp_add_inline_style` hinzu: + +```css +#tsparticles-background { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + z-index: -1; + pointer-events: none; +} + +/* Stellen Sie sicher, dass der Inhalt über den Partikeln erscheint */ +.site-content { + position: relative; + z-index: 1; +} +``` + +### Bedingtes Laden + +Um tsParticles nur auf bestimmten Seiten zu laden: + +```php +// In functions.php — nur auf der Startseite einreihen +add_action('wp', function () { + if (is_front_page()) { + add_filter('tsparticles_options', function (array $options): array { + $options['particles']['number']['value'] = 120; + $options['particles']['color']['value'] = '#ffffff'; + $options['particles']['move']['speed'] = 0.8; + $options['background']['color'] = '#1a1a2e'; + return $options; + }); + } +}); +``` + +Kombinieren Sie dies mit der Block- oder Shortcode-Platzierung für einen leistungsfähigen, seiten-spezifischen Partikel-Hintergrund. + +--- + +Sie haben jetzt alles, was Sie benötigen, um tsParticles in eine WordPress-Seite zu integrieren. Egal, ob Sie den Block-Editor, Shortcodes oder die vollständige PHP-Steuerung bevorzugen, jeder Ansatz gibt Ihnen einen einzigartigen Partikel-Hintergrund mit minimalem Aufwand. diff --git a/websites/website/docs/es/guide/bundles-all.md b/websites/website/docs/es/guide/bundles-all.md index 33dad2d889b..ea1c1e98e07 100644 --- a/websites/website/docs/es/guide/bundles-all.md +++ b/websites/website/docs/es/guide/bundles-all.md @@ -1,21 +1,42 @@ # Bundle: All -`@tsparticles/all` carga todas las funciones oficiales y es ideal para prototipado rapido. +`@tsparticles/all` carga **todo** el repositorio tsParticles: cada forma, interacción, updater, efecto, ruta, easing, plugin y exportación. Es el bundle más grande, pensado para prototipado y demos. -## Cuando elegir All +## Funcionalidades incluidas -- Quieres todas las funciones disponibles de inmediato. -- Estas explorando opciones rapidamente. -- El tamano del bundle no es el limite principal. +Hereda todo de `tsparticles` (full) más: -## Instalacion +**Todas las formas:** arrow, cards, cog, heart, infinity, matrix, path, ribbon, rounded-polygon, rounded-rect, spiral, squircle + +**Todas las interacciones:** cannon, light, particle, pop, particles-repulse + +**Todos los efectos:** bubble, filter, particles, shadow, trail + +**Todos los generadores de path:** branches, brownian, curl-noise, curves, fractal-noise, grid, levy, perlin-noise, polygon, random, simplex-noise, spiral, svg, zig-zag + +**Todos los easing:** back, bounce, circ, cubic, elastic, expo, gaussian, linear, quad, quart, quint, sigmoid, sine, smoothstep + +**Todos los plugins de color:** HEX, HSL, RGB, HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH + +**Todos los plugins:** absorbers, background-mask, canvas-mask, emitters (con todas las formas), easing (todos), export-image, export-json, export-video, infection, manual-particles, motion, poisson-disc, polygon-mask, responsive, sounds, themes, trail, zoom + +**Todos los updaters:** destroy, gradient, life, opacity, orbit, out-modes, paint, roll, rotate, size, tilt, twinkle, wobble + +## Cuándo usarlo + +- Prototipado rápido para explorar las posibilidades +- Demos y showcases +- Entornos de desarrollo donde el tamaño no es importante +- **No recomendado en producción**: prefiere bundles más específicos + +## Instalación + +### Con npm/pnpm/yarn ```bash pnpm add @tsparticles/engine @tsparticles/all ``` -## Ejemplo de setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadAll } from "@tsparticles/all"; @@ -25,20 +46,48 @@ await loadAll(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { number: { value: 100 }, + shape: { type: "heart" }, move: { enable: true, speed: 2 }, }, }, }); ``` +### Con CDN (etiqueta ` + + +``` + +## Diferencia entre `tsparticles` y `@tsparticles/all` + +Ver la tabla completa en la [página bundles-full](/es/guide/bundles-full) para la comparación detallada. + ## Errores comunes -- Usarlo en produccion cuando un bundle mas enfocado seria mejor. -- Llamar `tsParticles.load(...)` antes de `loadAll(...)`. +- Usarlo en producción — prefiere `@tsparticles/slim` o `tsparticles` para bundles más pequeños. +- Llamar `tsParticles.load()` antes de `loadAll(tsParticles)`. -## Paginas relacionadas +## Ver también -- Vista general: [`/guide/bundles`](/es/guide/bundles) -- Matriz de instalacion: [`/guide/installation`](/es/guide/installation) +- [Panorámica de bundles](/es/guide/bundles) +- [Guía de instalación](/es/guide/installation) diff --git a/websites/website/docs/es/guide/bundles-basic.md b/websites/website/docs/es/guide/bundles-basic.md index bb07092a23e..99acb2f511f 100644 --- a/websites/website/docs/es/guide/bundles-basic.md +++ b/websites/website/docs/es/guide/bundles-basic.md @@ -1,21 +1,46 @@ # Bundle: Basic -`@tsparticles/basic` esta pensado para configuraciones muy ligeras con runtime minimo. +`@tsparticles/basic` es el bundle más ligero. Incluye solo lo esencial: círculos que se mueven con opacidad y tamaño animables. -## Cuando elegir Basic +## Funcionalidades incluidas -- El tamano del bundle es tu prioridad principal. -- Solo necesitas efectos base. -- No necesitas plugins avanzados. +**Formas:** círculo -## Instalacion +**Updaters (animaciones):** + +- paint (color) +- opacity (opacidad) +- out-modes (comportamiento al salir de la pantalla) +- size (tamaño) + +**Plugins:** + +- move (movimiento) +- blend (mezcla de color) +- Colores HEX, HSL, RGB + +**No incluye:** + +- Interacciones mouse/touch (click, hover, etc.) +- Enlaces entre partículas (links) +- Otras formas (cuadrados, estrellas, imágenes, polígonos, etc.) +- Emisores, absorbedores, sonidos +- Rotación, vida, roll, tilt, wobble + +## Cuándo usarlo + +- El tamaño del bundle es la prioridad absoluta +- Solo se necesitan puntos que se muevan +- No se necesitan interacciones ni formas complejas + +## Instalación + +### Con npm/pnpm/yarn ```bash pnpm add @tsparticles/engine @tsparticles/basic ``` -## Ejemplo de setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadBasic } from "@tsparticles/basic"; @@ -25,20 +50,48 @@ await loadBasic(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#ffffff" }, particles: { number: { value: 50 }, - move: { enable: true, speed: 1.5 }, + color: { value: ["#5bc0eb", "#fde74c", "#9bc53d"] }, + size: { + value: { min: 300, max: 400 }, + animation: { enable: true, speed: 100 }, + }, + move: { enable: true, speed: 10 }, }, }, }); ``` +### Con CDN (etiqueta ` + + +``` + ## Errores comunes -- Esperar funciones que dependen de plugins no incluidos. -- Llamar `tsParticles.load(...)` antes de `loadBasic(...)`. +- Esperar funcionalidades que no están incluidas (ej. `links`, interacciones mouse), que requieren bundles superiores. +- Llamar `tsParticles.load()` antes de `loadBasic(tsParticles)`: las formas y updaters aún no están registrados. +- Instalar solo `@tsparticles/engine` sin un bundle: el engine por sí solo no dibuja nada. -## Paginas relacionadas +## Ver también -- Vista general: [`/guide/bundles`](/es/guide/bundles) -- Matriz de instalacion: [`/guide/installation`](/es/guide/installation) +- [Panorámica de bundles](/es/guide/bundles) +- [Guía de instalación](/es/guide/installation) diff --git a/websites/website/docs/es/guide/bundles-confetti.md b/websites/website/docs/es/guide/bundles-confetti.md index ba7043e265a..de5f8b5a78a 100644 --- a/websites/website/docs/es/guide/bundles-confetti.md +++ b/websites/website/docs/es/guide/bundles-confetti.md @@ -1,42 +1,83 @@ # Bundle: Confetti -`@tsparticles/confetti` expone una API enfocada para efectos de confeti con setup minimo. +`@tsparticles/confetti` expone una API simplificada para crear efectos de confeti con una sola llamada a función. No requiere interactuar con `tsParticles` directamente. -## Cuando elegir Confetti +## Funcionalidades incluidas -- Quieres efectos de celebracion en una sola llamada. -- No necesitas cablear el engine manualmente. -- Prefieres una API compacta para eventos de UI. +**Formas:** círculo, corazón, cartas (palos franceses: corazones, diamantes, tréboles, picas), emoji, imágenes, polígono, cuadrado, estrella -## Instalacion +**Plugins internos:** emisores, motion (respeta las preferencias de usuario de reducir animaciones) + +**Updaters:** life, roll, rotate, tilt, wobble + +**API:** `confetti(options)` o `confetti(canvasId, options)` + +## Cuándo usarlo + +- Botón "¡Felicidades!" o "¡Cumpleaños!" +- Efecto de celebración rápido +- No quieres configurar el engine manualmente + +## Instalación + +### Con npm/pnpm/yarn ```bash pnpm add @tsparticles/confetti ``` -## Ejemplo de setup - ```ts import { confetti } from "@tsparticles/confetti"; +// Efecto base await confetti({ - count: 80, - spread: 60, + particleCount: 100, + spread: 70, + origin: { x: 0.5, y: 0.5 }, }); -await confetti("canvas-id", { - count: 50, +// En un canvas específico +await confetti("my-canvas-id", { + particleCount: 50, angle: 90, spread: 45, + colors: ["#ff0000", "#00ff00", "#0000ff"], }); ``` +### Con CDN (etiqueta ` + +``` + +### Parámetros principales + +| Parámetro | Tipo | Default | Descripción | +| --------------- | -------- | ------------ | ---------------------------------------------------- | +| `particleCount` | number | 50 | Número de confetis | +| `spread` | number | 60 | Ángulo de difusión (grados) | +| `angle` | number | 90 | Dirección (grados, 90 = abajo) | +| `startVelocity` | number | 30 | Velocidad inicial | +| `colors` | string[] | — | Colores de los confetis | +| `origin` | { x, y } | { 0.5, 0.5 } | Punto de origen (0-1) | +| `drift` | number | 0 | Deriva horizontal | +| `shapes` | string[] | — | Formas: "circle", "heart", "square", "star", "cards" | + ## Errores comunes -- Asumir que `tsParticles` se exporta desde `@tsparticles/confetti`. -- Reusar el mismo id de canvas sin querer. +- Pensar que `tsParticles` se exporta desde `@tsparticles/confetti` — no es así. +- Reutilizar el mismo ID de canvas sin querer. +- Llamar `confetti` en bucle sin gestionar el rendimiento: usa un intervalo razonable o detén la animación cuando no sea necesaria. -## Paginas relacionadas +## Ver también -- Vista general: [`/guide/bundles`](/es/guide/bundles) -- Bundles del playground: [`/playground/bundles`](/es/playground/bundles) +- [Panorámica de bundles](/es/guide/bundles) +- [Bundle fireworks](/es/guide/bundles-fireworks) diff --git a/websites/website/docs/es/guide/bundles-fireworks.md b/websites/website/docs/es/guide/bundles-fireworks.md index 8533b5c47d1..c1640c686e5 100644 --- a/websites/website/docs/es/guide/bundles-fireworks.md +++ b/websites/website/docs/es/guide/bundles-fireworks.md @@ -1,44 +1,81 @@ # Bundle: Fireworks -`@tsparticles/fireworks` expone una API enfocada para efectos de fuegos artificiales con setup minimo. +`@tsparticles/fireworks` expone una API simplificada para crear efectos de fuegos artificiales con una sola llamada. Soporta sonidos, colores personalizados y control de la instancia (pause/play). -## Cuando elegir Fireworks +## Funcionalidades incluidas -- Quieres animaciones fireworks en una sola llamada. -- No necesitas wiring directo del engine. -- Prefieres una API compacta para momentos de celebracion. +**Formas:** línea, círculo (de basic) -## Instalacion +**Plugins internos:** emisores, emitters-shape-square, blend (mezcla), sonidos (sounds) + +**Updaters:** destroy, life, paint, rotate + +**API:** `fireworks(options)`, devuelve una instancia controlable + +## Cuándo usarlo + +- Efecto de Año Nuevo o fiesta +- UI de celebración +- No quieres configurar el engine manualmente + +## Instalación + +### Con npm/pnpm/yarn ```bash pnpm add @tsparticles/fireworks ``` -## Ejemplo de setup - ```ts import { fireworks } from "@tsparticles/fireworks"; +// Efecto base const instance = await fireworks({ - colors: ["#ffffff", "#ff0000"], - sounds: false, + colors: ["#ffffff", "#ff0000", "#00ff00", "#0000ff"], + sounds: true, }); +// Control de instancia instance?.pause(); instance?.play(); -await fireworks("canvas-id", { +// En un canvas específico +await fireworks("my-canvas", { rate: 3, speed: { min: 10, max: 25 }, + sounds: false, }); ``` +### Con CDN (etiqueta ` + +``` + +### Parámetros principales + +| Parámetro | Tipo | Default | Descripción | +| ------------ | ------------ | ------- | -------------------------- | +| `colors` | string[] | — | Colores de explosión | +| `rate` | number | — | Fuegos por segundo | +| `speed` | { min, max } | — | Velocidad de partículas | +| `sounds` | boolean | true | Habilita efectos de sonido | +| `gravity` | number | — | Gravedad (default: 0) | +| `opacity` | number | — | Opacidad (0-1) | +| `brightness` | { min, max } | — | Brillo de explosión | + ## Errores comunes -- Asumir que `tsParticles` se exporta desde `@tsparticles/fireworks`. -- Llamar `fireworks(...)` repetidamente sin manejar la instancia. +- Pensar que `tsParticles` se exporta desde `@tsparticles/fireworks` — no es así. +- Llamar `fireworks()` en bucle sin gestionar la instancia: el efecto ya es continuo, no hace falta un intervalo. +- No detener la instancia cuando el usuario cambia de página: llama `instance?.pause()` o `instance?.stop()`. -## Paginas relacionadas +## Ver también -- Vista general: [`/guide/bundles`](/es/guide/bundles) -- Bundles del playground: [`/playground/bundles`](/es/playground/bundles) +- [Panorámica de bundles](/es/guide/bundles) +- [Bundle confetti](/es/guide/bundles-confetti) diff --git a/websites/website/docs/es/guide/bundles-full.md b/websites/website/docs/es/guide/bundles-full.md index 729f73e48e5..7b4bb54ee1c 100644 --- a/websites/website/docs/es/guide/bundles-full.md +++ b/websites/website/docs/es/guide/bundles-full.md @@ -1,21 +1,48 @@ # Bundle: tsparticles (Full) -`tsparticles` es el bundle full e incluye un conjunto amplio de funciones oficiales con un unico loader. +`tsparticles` (npm: `tsparticles`, loader: `loadFull`) es el bundle oficial completo. Incluye todas las funcionalidades del bundle Slim más emisores, absorbedores, formas de texto, animaciones avanzadas (wobble, roll, tilt, twinkle, destroy). -## Cuando elegir tsparticles (Full) +## Funcionalidades incluidas -- Necesitas muchas funciones oficiales sin seleccionar plugins manualmente. -- Quieres una base completa lista para produccion antes de afinar. -- Prefieres control del engine con la API `tsParticles`. +Hereda todo de `@tsparticles/slim` más: -## Instalacion +**Formas adicionales:** text (texto con fuentes personalizadas) + +**Interacciones externas adicionales:** + +- drag (arrastrar partículas con el mouse) +- trail (estela detrás del mouse) + +**Updaters adicionales:** + +- destroy (destrucción de partículas con animación) +- roll (rodamiento) +- tilt (inclinación 3D) +- twinkle (centelleo intermitente) +- wobble (oscilación) + +**Plugins:** + +- absorbers (absorbedores — agujeros negros que succionan partículas) +- emitters (emisores — fuentes continuas de partículas) +- emitters-shape-circle, emitters-shape-square (formas para emisores) + +## Cuándo usarlo + +- Se necesitan emisores (partículas que aparecen continuamente) +- Se necesitan absorbedores (partículas que son succionadas) +- Se necesitan formas de texto con fuentes personalizadas +- Se necesitan animaciones avanzadas (wobble, tilt, roll, twinkle) +- Buen punto de llegada antes de pasar a plugins individuales + +## Instalación + +### Con npm/pnpm/yarn ```bash pnpm add @tsparticles/engine tsparticles ``` -## Ejemplo de setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadFull } from "tsparticles"; @@ -25,20 +52,65 @@ await loadFull(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { - number: { value: 100 }, - move: { enable: true, speed: 2 }, + number: { value: 50 }, + shape: { type: "text", options: { text: ["🔥", "✨", "⭐"] } }, + size: { value: 24 }, + move: { enable: true, speed: 1 }, + wobble: { enable: true, distance: 10 }, + }, + emitters: { + direction: "top", + rate: { quantity: 2, delay: 0.3 }, }, }, }); ``` +### Con CDN (etiqueta ` + + +``` + +## Diferencia entre `tsparticles` y `@tsparticles/all` + +| Aspecto | `tsparticles` (full) | `@tsparticles/all` | +| ------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| Tamaño | Contenido | Muy grande | +| Formas | circle, square, star, polygon, line, image, emoji, text | Todas las formas (corazón, cartas, flechas, espirales, cog, rounded-rect, etc.) | +| Interacciones | Slim + drag + trail | Todas (cannon, light, pop, particle, repulse) | +| Path | Solo easing quad | 14 generadores de path | +| Efectos | Ninguno | 5 efectos (bubble, filter, shadow, etc.) | +| Exportaciones | Ninguna | Image, JSON, Video | +| Plugins extra | absorbers, emitters | Todos (sounds, themes, trail, zoom, polygon-mask, canvas-mask, background-mask, etc.) | +| Easing | Quad | 15 easing | + ## Errores comunes -- Llamar `tsParticles.load(...)` antes de `loadFull(...)`. -- Asumir que es el mismo paquete que `@tsparticles/all` (son bundles diferentes). +- Confundir `tsparticles` con `@tsparticles/all` — no son el mismo paquete. +- Llamar `tsParticles.load()` antes de `loadFull(tsParticles)`. +- El paquete npm es `tsparticles` (no `@tsparticles/full`), el loader es `loadFull`. -## Paginas relacionadas +## Ver también -- Vista general: [`/guide/bundles`](/es/guide/bundles) -- Matriz de instalacion: [`/guide/installation`](/es/guide/installation) +- [Panorámica de bundles](/es/guide/bundles) +- [Guía de instalación](/es/guide/installation) diff --git a/websites/website/docs/es/guide/bundles-particles.md b/websites/website/docs/es/guide/bundles-particles.md index 8b95810253c..1d0c4439ea1 100644 --- a/websites/website/docs/es/guide/bundles-particles.md +++ b/websites/website/docs/es/guide/bundles-particles.md @@ -1,42 +1,98 @@ # Bundle: Particles -`@tsparticles/particles` expone una API enfocada para fondos de particulas simples. +`@tsparticles/particles` expone una API simplificada para crear fondos de partículas interactivos. Es una alternativa más completa a `@tsparticles/basic` pero con API dedicada en lugar de configurar el engine manualmente. -## Cuando elegir Particles +## Funcionalidades incluidas -- Quieres una API rapida para fondos de particulas. -- No necesitas configurar engine/plugins manualmente. -- Prefieres una API compacta tipo app. +**Formas:** círculo (de basic) -## Instalacion +**Plugins internos:** interactivity (enlaces, colisiones) + +**Interacciones:** links (enlaces entre partículas), collisions (colisiones) + +**API:** `particles(options)` o `particles(canvasId, options)` + +## Cuándo usarlo + +- Fondo de partículas para un sitio web +- Fondo con enlaces entre partículas (estilo "nodos") +- No quieres configurar el engine manualmente + +## Instalación + +### Con npm/pnpm/yarn ```bash pnpm add @tsparticles/particles ``` -## Ejemplo de setup - ```ts import { particles } from "@tsparticles/particles"; +// Fondo con enlaces await particles({ count: 120, links: true, - linksColor: "#0ff", + color: "#ffffff", + linksColor: "#00d8ff", + radius: 3, + speed: 2, + opacity: 0.8, }); -await particles("canvas-id", { +// En un canvas específico +await particles("my-canvas", { count: 80, shape: ["circle", "square"], + links: true, }); + +// Con colores personalizados +await particles({ + count: 100, + color: ["#ff6b6b", "#4ecdc4", "#45b7d1"], + links: false, +}); +``` + +### Con CDN (etiqueta ` + ``` +### Parámetros principales + +| Parámetro | Tipo | Default | Descripción | +| ------------ | ------------------ | ---------- | ----------------------- | +| `count` | number | 50 | Número de partículas | +| `radius` | number | 3 | Radio de partículas | +| `speed` | number | 2 | Velocidad de movimiento | +| `opacity` | number | 0.8 | Opacidad (0-1) | +| `color` | string \| string[] | "#ffffff" | Color/es de partículas | +| `links` | boolean | false | Muestra enlaces | +| `linksColor` | string | "#ffffff" | Color de enlaces | +| `linksWidth` | number | 1 | Grosor de enlaces | +| `shape` | string[] | ["circle"] | Formas de partículas | + ## Errores comunes -- Asumir que `tsParticles` se exporta desde `@tsparticles/particles`. -- Reusar el mismo id de canvas sin querer. +- Pensar que `tsParticles` se exporta desde `@tsparticles/particles` — no es así. +- Reutilizar el mismo ID de canvas sin querer. +- Esperar formas avanzadas (estrellas, polígonos) — el bundle particles está basado en basic y usa solo círculos. -## Paginas relacionadas +## Ver también -- Vista general: [`/guide/bundles`](/es/guide/bundles) -- Bundles del playground: [`/playground/bundles`](/es/playground/bundles) +- [Panorámica de bundles](/es/guide/bundles) +- [Guía para empezar](/es/guide/getting-started) diff --git a/websites/website/docs/es/guide/bundles-slim.md b/websites/website/docs/es/guide/bundles-slim.md index 8dfb101d3a7..8e6a5e4926a 100644 --- a/websites/website/docs/es/guide/bundles-slim.md +++ b/websites/website/docs/es/guide/bundles-slim.md @@ -1,21 +1,61 @@ # Bundle: Slim -`@tsparticles/slim` es la opcion recomendada para la mayoria de proyectos. +`@tsparticles/slim` es el bundle recomendado para la mayoría de proyectos. Incluye todo lo necesario para crear animaciones de partículas modernas con interacciones mouse, formas múltiples y enlaces. -## Cuando elegir Slim +## Funcionalidades incluidas -- Quieres buen equilibrio entre peso y funciones. -- Usas la API de engine `tsParticles` directamente. -- Necesitas formas/interacciones comunes sin cargar todo. +Hereda todo de `@tsparticles/basic` más: -## Instalacion +**Formas:** círculo, cuadrado, estrella, polígono, línea, imagen, emoji + +**Interacciones externas (mouse/touch):** + +- attract +- bounce +- bubble +- connect +- destroy +- grab +- parallax +- pause +- push +- remove +- repulse +- slow + +**Interacciones entre partículas:** + +- attract +- collisions (colisiones) +- links (enlaces entre partículas) + +**Updaters adicionales:** + +- life (vida/ciclo) +- rotate (rotación) + +**Plugins:** + +- interactivity (plugin para habilitar las interacciones) +- easing-quad (easing cuadrático para animaciones) +- Colores HEX, HSL, RGB + +## Cuándo usarlo + +- Punto de partida recomendado para la mayoría de proyectos +- Se necesitan formas múltiples (círculos, estrellas, polígonos, imágenes) +- Se necesitan interacciones mouse (click, hover, bubble, repulse) +- Se necesitan enlaces entre partículas (links) +- Buen equilibrio entre tamaño del bundle y funcionalidades + +## Instalación + +### Con npm/pnpm/yarn ```bash pnpm add @tsparticles/engine @tsparticles/slim ``` -## Ejemplo de setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; @@ -25,21 +65,47 @@ await loadSlim(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#0b1020" }, particles: { number: { value: 80 }, + links: { enable: true, distance: 150 }, move: { enable: true, speed: 2 }, - links: { enable: true }, + shape: { type: ["circle", "star", "square"] }, }, }, }); ``` +### Con CDN (etiqueta ` + + +``` + ## Errores comunes -- Llamar `tsParticles.load(...)` antes de `loadSlim(...)`. -- Mezclar versiones entre engine y plugins. +- Llamar `tsParticles.load()` antes de `loadSlim(tsParticles)`. +- Mezclar versiones diferentes entre engine y bundle — mantenlos alineados. +- Esperar funcionalidades que solo están en bundles superiores (emisores, absorbedores, texto, wobble): se necesita `tsparticles` (full) o plugins individuales. -## Paginas relacionadas +## Ver también -- Vista general: [`/guide/bundles`](/es/guide/bundles) -- Matriz de instalacion: [`/guide/installation`](/es/guide/installation) +- [Panorámica de bundles](/es/guide/bundles) +- [Guía de instalación](/es/guide/installation) diff --git a/websites/website/docs/es/guide/bundles.md b/websites/website/docs/es/guide/bundles.md index 02d54c0b0ae..4f753e6797e 100644 --- a/websites/website/docs/es/guide/bundles.md +++ b/websites/website/docs/es/guide/bundles.md @@ -1,104 +1,184 @@ -# Guia de bundles - -Esta pagina te ayuda a elegir el bundle correcto de `tsParticles` y configurarlo rapido. - -## Comparacion de paquetes - -| Paquete | Ideal para | Estilo de setup | -| ------------------------ | --------------------------------------------------------------- | ---------------------------------------------- | -| `@tsparticles/basic` | Configuraciones ultra ligeras | `tsParticles` + `await loadBasic(tsParticles)` | -| `@tsparticles/slim` | La mayoria de sitios/apps | `tsParticles` + `await loadSlim(tsParticles)` | -| `tsparticles` | Conjunto completo de funciones oficiales con control del engine | `tsParticles` + `await loadFull(tsParticles)` | -| `@tsparticles/all` | Todas las funciones, prototipado rapido | `tsParticles` + `await loadAll(tsParticles)` | -| `@tsparticles/confetti` | Efectos de confeti con una llamada | `await confetti(options)` | -| `@tsparticles/fireworks` | Efectos de fuegos artificiales con una llamada | `await fireworks(options)` | -| `@tsparticles/particles` | API simple para fondo de particulas | `await particles(options)` | -| `@tsparticles/ribbons` | Efectos de ribbons con una llamada | `await ribbons(options)` | - -## Guias por bundle - -- Basic: [`/guide/bundles-basic`](/es/guide/bundles-basic) -- Slim: [`/guide/bundles-slim`](/es/guide/bundles-slim) -- tsparticles (Full): [`/guide/bundles-full`](/es/guide/bundles-full) -- All: [`/guide/bundles-all`](/es/guide/bundles-all) -- Confetti: [`/guide/bundles-confetti`](/es/guide/bundles-confetti) -- Fireworks: [`/guide/bundles-fireworks`](/es/guide/bundles-fireworks) -- Particles: [`/guide/bundles-particles`](/es/guide/bundles-particles) -- Ribbons (demo + docs): [`/demos/recipes/ribbons`](/es/demos/recipes/ribbons) · - -## Instalacion - -Instala la ruta de paquetes que coincide con tu caso de uso. - -```bash -pnpm add @tsparticles/engine @tsparticles/basic -pnpm add @tsparticles/engine @tsparticles/slim -pnpm add @tsparticles/engine tsparticles -pnpm add @tsparticles/engine @tsparticles/all -pnpm add @tsparticles/confetti -pnpm add @tsparticles/fireworks -pnpm add @tsparticles/particles -pnpm add @tsparticles/ribbons +# Guía de bundles + +tsParticles es modular. El paquete `@tsparticles/engine` contiene solo el motor base; para tener efectos visibles debes registrar **formas** (qué dibujar), **updaters** (cómo animar), **interacciones** (cómo reaccionar a mouse/touch) y **plugins** (funcionalidades extra). Todo esto ocurre a través de los **bundles**. + +## Categorías de bundles + +| Categoría | Bundle | API | +| --------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------- | +| Engine + loader | `@tsparticles/basic`, `@tsparticles/slim`, `tsparticles`, `@tsparticles/all` | `tsParticles.load({ id, options })` | +| API dedicada | `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles`, `@tsparticles/ribbons` | `confetti({...})`, `fireworks({...})`, etc. | + +## Tabla comparativa completa + +Leyenda: ● = incluido, ○ = no incluido + +| Funcionalidad | basic | slim | full (`tsparticles`) | all | +| --------------------------------------------------------------------------------------------------- | ----- | ---- | -------------------- | ------------------ | +| **Formas (shape)** | | | | | +| Círculo (circle) | ● | ● | ● | ● | +| Cuadrado (square) | ○ | ● | ● | ● | +| Estrella (star) | ○ | ● | ● | ● | +| Polígono (polygon) | ○ | ● | ● | ● | +| Línea (line) | ○ | ● | ● | ● | +| Imagen (image) | ○ | ● | ● | ● | +| Emoji | ○ | ● | ● | ● | +| Texto (text) | ○ | ○ | ● | ● | +| Cartas (cards) | ○ | ○ | ○ | ● | +| Corazón (heart) | ○ | ○ | ○ | ● | +| Flechas (arrow) | ○ | ○ | ○ | ● | +| Rounded rect | ○ | ○ | ○ | ● | +| Rounded polygon | ○ | ○ | ○ | ● | +| Espiral (spiral) | ○ | ○ | ○ | ● | +| Squircle | ○ | ○ | ○ | ● | +| Cog (engranaje) | ○ | ○ | ○ | ● | +| Infinito (infinity) | ○ | ○ | ○ | ● | +| Matriz (matrix) | ○ | ○ | ○ | ● | +| Path | ○ | ○ | ○ | ● | +| Ribbon | ○ | ○ | ○ | ● | +| **Interacciones externas (mouse/touch)** | | | | | +| Attract | ○ | ● | ● | ● | +| Bounce | ○ | ● | ● | ● | +| Bubble | ○ | ● | ● | ● | +| Connect | ○ | ● | ● | ● | +| Destroy | ○ | ● | ● | ● | +| Grab | ○ | ● | ● | ● | +| Parallax | ○ | ● | ● | ● | +| Pause | ○ | ● | ● | ● | +| Push | ○ | ● | ● | ● | +| Remove | ○ | ● | ● | ● | +| Repulse | ○ | ● | ● | ● | +| Slow | ○ | ● | ● | ● | +| Drag | ○ | ○ | ● | ● | +| Trail | ○ | ○ | ● | ● | +| Cannon | ○ | ○ | ○ | ● | +| Particle | ○ | ○ | ○ | ● | +| Pop | ○ | ○ | ○ | ● | +| Light | ○ | ○ | ○ | ● | +| **Interacciones entre partículas** | | | | | +| Links (enlaces) | ○ | ● | ● | ● | +| Collisions (colisiones) | ○ | ● | ● | ● | +| Attract | ○ | ● | ● | ● | +| Repulse | ○ | ○ | ○ | ● | +| **Updaters (animaciones)** | | | | | +| Opacidad | ● | ● | ● | ● | +| Tamaño (size) | ● | ● | ● | ● | +| Out modes (salida pantalla) | ● | ● | ● | ● | +| Paint (color) | ● | ● | ● | ● | +| Rotación (rotate) | ○ | ● | ● | ● | +| Life (vida/ciclo) | ○ | ● | ● | ● | +| Destroy (destrucción) | ○ | ○ | ● | ● | +| Roll (rodamiento) | ○ | ○ | ● | ● | +| Tilt (inclinación) | ○ | ○ | ● | ● | +| Twinkle (centelleo) | ○ | ○ | ● | ● | +| Wobble (oscilación) | ○ | ○ | ● | ● | +| Gradient | ○ | ○ | ○ | ● | +| Orbit | ○ | ○ | ○ | ● | +| **Plugins** | | | | | +| Move (movimiento) | ● | ● | ● | ● | +| Blend (mezcla) | ● | ● | ● | ● | +| Emisores (emitters) | ○ | ○ | ● | ● | +| Absorbedores (absorbers) | ○ | ○ | ● | ● | +| Sonidos (sounds) | ○ | ○ | ○ | ● | +| Motion (preferencias usuario) | ○ | ○ | ○ | ● | +| Temas (themes) | ○ | ○ | ○ | ● | +| Polygon mask | ○ | ○ | ○ | ● | +| Canvas mask | ○ | ○ | ○ | ● | +| Background mask | ○ | ○ | ○ | ● | +| Export (imagen, json, video) | ○ | ○ | ○ | ● | +| Manual particles | ○ | ○ | ○ | ● | +| Responsive | ○ | ○ | ○ | ● | +| Trail | ○ | ○ | ○ | ● | +| Zoom | ○ | ○ | ○ | ● | +| Poisson disc | ○ | ○ | ○ | ● | +| **Rutas (path)** | | | | | +| Cualquier path | ○ | ○ | ○ | ● (14 generadores) | +| **Efectos** | | | | | +| Bubble, Filter, Shadow, etc. | ○ | ○ | ○ | ● (5 efectos) | +| **Easing** | | | | | +| Quad | ○ | ● | ● | ● | +| Back, Bounce, Circ, Cubic, Elastic, Expo, Gaussian, Linear, Quart, Quint, Sigmoid, Sine, Smoothstep | ○ | ○ | ○ | ● | +| **Plugins de color** | | | | | +| HEX, HSL, RGB | ● | ● | ● | ● | +| HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH | ○ | ○ | ○ | ● | + +### Bundles con API dedicada + +| Funcionalidad | confetti | fireworks | particles | ribbons | +| ------------------ | --------------------------------------------------------------------- | ------------------------ | ------------------ | ---------------- | +| Formas | círculo, corazón, cartas, emoji, imagen, polígono, cuadrado, estrella | línea | (de basic) | ribbon | +| Interacciones | — | — | links + colisiones | — | +| Plugins especiales | emisores, motion | emisores, sonidos, blend | — | emisores, motion | +| API llamada | `confetti(opts)` | `fireworks(opts)` | `particles(opts)` | `ribbons(opts)` | + +## Guía de selección + +```mermaid +flowchart TD + A[¿Debo empezar rápido?] -->|Sí| B[¿Uso un preset?] + A -->|No| C[¿Qué tamaño de bundle?] + B -->|Sí| D["@tsparticles/configs + @tsparticles/slim"] + B -->|No| E["¿Confeti? → @tsparticles/confetti"] + B -->|No| F["¿Fuegos? → @tsparticles/fireworks"] + B -->|No| G["¿Fondo partículas? → @tsparticles/particles"] + B -->|No| H["¿Cintas? → @tsparticles/ribbons"] + C -->|"Mínimo (solo círculos)"| I["@tsparticles/basic"] + C -->|"Medio (formas + interacciones)"| J["@tsparticles/slim"] + C -->|"Máximo (todas las funcionalidades)"| K["tsparticles (loadFull)"] + C -->|"Todo el repositorio"| L["@tsparticles/all"] ``` -Necesitas enlaces CDN y mas variantes de gestores de paquetes? - -- Ver [`/guide/installation`](/es/guide/installation). - -## Ejemplos de setup - -### Bundles con engine + loader (`basic`, `slim`, `full`, `all`) - -```ts -import { tsParticles } from "@tsparticles/engine"; -import { loadSlim } from "@tsparticles/slim"; - -await loadSlim(tsParticles); - -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - number: { value: 80 }, - move: { enable: true, speed: 2 }, - }, - }, -}); +**Reglas prácticas:** + +1. La mayoría de proyectos parten de `@tsparticles/slim`. +2. Si el tamaño del bundle es crítico y solo se necesitan círculos que se muevan: `@tsparticles/basic`. +3. Si se necesitan emisores, absorbedores, texto, wobble/tilt/roll: `tsparticles` con `loadFull`. +4. Para prototipado rápido con todas las funcionalidades: `@tsparticles/all`. +5. Para efectos específicos (confeti, fuegos, partículas, cintas) con configuración mínima: bundles con API dedicada. + +## Instalación rápida + +| Bundle | Comando npm | Función loader | URL CDN | +| ------------------------ | ------------------------------------------------- | ------------------------ | -------------------------------------------------------------- | +| `@tsparticles/basic` | `pnpm add @tsparticles/engine @tsparticles/basic` | `loadBasic(tsParticles)` | `@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| `@tsparticles/slim` | `pnpm add @tsparticles/engine @tsparticles/slim` | `loadSlim(tsParticles)` | `@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| `tsparticles` (full) | `pnpm add @tsparticles/engine tsparticles` | `loadFull(tsParticles)` | `tsparticles@4/tsparticles.bundle.min.js` | +| `@tsparticles/all` | `pnpm add @tsparticles/engine @tsparticles/all` | `loadAll(tsParticles)` | `@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| `@tsparticles/confetti` | `pnpm add @tsparticles/confetti` | `confetti(opts)` | `@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| `@tsparticles/fireworks` | `pnpm add @tsparticles/fireworks` | `fireworks(opts)` | `@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| `@tsparticles/particles` | `pnpm add @tsparticles/particles` | `particles(opts)` | `@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| `@tsparticles/ribbons` | `pnpm add @tsparticles/ribbons` | `ribbons(opts)` | `@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | + +**Nota:** con los bundles basic/slim/full/all DEBES llamar a `load*` antes de `tsParticles.load()`. Los archivos CDN exponen la función loader globalmente pero NO la llaman automáticamente. Los bundles confetti/fireworks/particles/ribbons tienen API autónoma — llama directamente a `confetti()`, `fireworks()`, etc. + +Ejemplo CDN para `@tsparticles/slim`: + +```html + + + ``` -Para los otros presets, cambia solo el import/funcion del loader: +Ejemplo CDN para `@tsparticles/confetti`: -- `@tsparticles/basic` -> `loadBasic` -- `tsparticles` -> `loadFull` -- `@tsparticles/all` -> `loadAll` - -### API enfocadas (`confetti`, `fireworks`, `particles`, `ribbons`) - -```ts -import { confetti } from "@tsparticles/confetti"; -import { fireworks } from "@tsparticles/fireworks"; -import { particles } from "@tsparticles/particles"; -import { ribbons } from "@tsparticles/ribbons"; - -await confetti({ count: 80, spread: 60 }); -await fireworks({ sounds: false }); -await particles({ count: 100, links: true }); -await ribbons({ count: 5, spread: 0 }); +```html + + ``` -Estas API son ideales cuando quieres integracion rapida sin conectar manualmente muchos plugins del engine. - -## Reglas practicas de seleccion - -1. Empieza con `@tsparticles/slim` en la mayoria de proyectos. -2. Usa `@tsparticles/basic` si el tamano del bundle es tu prioridad principal y las funciones son simples. -3. Usa `tsparticles` cuando necesites una base full con muchas funciones y `loadFull`. -4. Usa `@tsparticles/all` para prototipado o cuando necesites muchas funciones de inmediato. -5. Usa `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles` o `@tsparticles/ribbons` cuando tu UI necesite un efecto enfocado con setup minimo. +Ver también la [guía de instalación](/es/guide/installation) para CDN, npm, yarn, y detalles sobre archivos. -## Paginas relacionadas +## Páginas relacionadas -- Bundles enfocados en playground: [`/playground/bundles`](/es/playground/bundles) -- Ruta de inicio: [`/guide/getting-started`](/es/guide/getting-started) -- Matriz de instalacion: [`/guide/installation`](/es/guide/installation) -- Vista general de wrappers: [`/guide/wrappers`](/es/guide/wrappers) +- [Guía para empezar](/es/guide/getting-started) +- [Guía de instalación](/es/guide/installation) +- [Catálogo de presets](/demos/presets) +- [Catálogo de paletas](/demos/palettes) +- [Catálogo de formas](/demos/shapes) diff --git a/websites/website/docs/es/guide/color-formats.md b/websites/website/docs/es/guide/color-formats.md index 388cfb81a87..3c43d3f2735 100644 --- a/websites/website/docs/es/guide/color-formats.md +++ b/websites/website/docs/es/guide/color-formats.md @@ -1,6 +1,6 @@ # Formatos de color -tsParticles acepta múltiples formatos de color en opciones como `background`, `particles.color` y configuraciones de complementos. +tsParticles acepta múltiples formatos de color en opciones como `background`, `particles.paint` y configuraciones de complementos. ## Formatos comunes diff --git a/websites/website/docs/es/guide/getting-started.md b/websites/website/docs/es/guide/getting-started.md index 34d35be985f..ae6a4d00dc8 100644 --- a/websites/website/docs/es/guide/getting-started.md +++ b/websites/website/docs/es/guide/getting-started.md @@ -1,106 +1,198 @@ # Primeros pasos -Esta ruta es la configuracion mas rapida y fiable para `tsParticles` en 2026. +tsParticles es una librería JavaScript/TypeScript para crear animaciones de partículas, confeti, fuegos artificiales y mucho más. Funciona en cualquier navegador moderno y está disponible como paquete npm o vía CDN con etiquetas ` + + + + +
+ + + +``` + +> **Nota**: incluso con los bundles CDN debes llamar `loadSlim(tsParticles)` (o `loadBasic` / `loadFull` / `loadAll`) antes de usar `tsParticles.load()`. Los bundles CDN exponen la función loader globalmente pero no la llaman automáticamente. -- `@tsparticles/slim`: la mayoria de apps deberian empezar aqui. -- `@tsparticles/basic`: conjunto mas pequeno para configuraciones muy ligeras. -- `@tsparticles/all`: todo incluido, ideal para prototipado rapido. +El mismo esquema aplica para `@tsparticles/basic` → `loadBasic`, `tsparticles` → `loadFull`, `@tsparticles/all` → `loadAll`. -Si necesitas una API enfocada en lugar de la configuracion directa de `tsParticles`: +### Ruta C — Bundles especializados con API dedicada (confeti, fuegos, partículas) -- `@tsparticles/particles`: API simplificada para fondo de particulas -- `@tsparticles/confetti`: API de confeti de una sola llamada -- `@tsparticles/fireworks`: API de fuegos artificiales de una sola llamada +Algunos bundles tienen su propia API simplificada, sin pasar por `tsParticles.load()`: + +```html + + + + + + + + + +``` -## 5) Usa presets/configs cuando necesites velocidad +Lo mismo para `fireworks()`, `particles()`, `ribbons()`. -Si prefieres efectos preconstruidos: +## ¿Qué bundle elegir? + +| Bundle | npm | Cuándo usarlo | +| ------------------------ | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `@tsparticles/basic` | `loadBasic(tsParticles)` | Mínimo indispensable: círculos, movimiento, opacidad, tamaño. | +| `@tsparticles/slim` | `loadSlim(tsParticles)` | **Elección recomendada para la mayoría de proyectos.** Añade interacciones (click/hover), enlaces entre partículas, imágenes, estrellas, polígonos. | +| `tsparticles` | `loadFull(tsParticles)` | Conjunto completo de funcionalidades oficiales: emisores, absorbedores, formas texto, roll, wobble, trail. | +| `@tsparticles/all` | `loadAll(tsParticles)` | **Todo** el repositorio: cada forma, interacción, efecto, easing, ruta, exportación. Solo para prototipado. | +| `@tsparticles/confetti` | `confetti(opciones)` | Confeti en una llamada. API dedicada. | +| `@tsparticles/fireworks` | `fireworks(opciones)` | Fuegos artificiales en una llamada. API dedicada. | +| `@tsparticles/particles` | `particles(opciones)` | Fondo de partículas simplificado. API dedicada. | +| `@tsparticles/ribbons` | `ribbons(opciones)` | Efecto ribbon/cintas. API dedicada. | + +Más detalles: [`/guide/bundles`](/es/guide/bundles). + +## Usar presets predefinidos + +El paquete `@tsparticles/configs` contiene decenas de configuraciones listas (absorbedores, burbujas, nieve, estrellas, gravity, collisions, etc.). ```bash -pnpm add @tsparticles/configs +pnpm add @tsparticles/engine @tsparticles/slim @tsparticles/configs ``` -Despues carga una configuracion por clave, como en la app [`demo/vite`](https://github.com/tsparticles/tsparticles/blob/main/demo/vite/src/main.ts). +```ts +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import "@tsparticles/configs"; -Si prefieres configuraciones basadas en nombre de preset, usa el catalogo oficial en [`/demos/presets`](/es/demos/presets). +await loadSlim(tsParticles); -## Mapa rapido de documentacion +// Carga un preset por nombre +await tsParticles.load({ + id: "tsparticles", + options: { preset: "snow" }, +}); +``` -- Opciones raiz: [`/options/`](/es/options/) -- Referencia de wrappers: [`/guide/wrappers`](/es/guide/wrappers) -- Catalogo de presets: [`/demos/presets`](/es/demos/presets) -- Catalogo de paletas: [`/demos/palettes`](/es/demos/palettes) -- Catalogo de formas: [`/demos/shapes`](/es/demos/shapes) -- Migracion desde particles.js: [`/migrations/particles-js`](/es/migrations/particles-js) -- Formatos de color: [`/guide/color-formats`](/es/guide/color-formats) -- Ciclo de vida del contenedor: [`/guide/container-lifecycle`](/es/guide/container-lifecycle) -- Plugins y personalizacion: [`/guide/plugins-customization`](/es/guide/plugins-customization) +Con CDN: -## Solucion de problemas +```html + + + + +``` + +## Referencias rápidas -- Pantalla en blanco: verifica que `#tsparticles` exista antes de llamar a `tsParticles.load`. -- Falta una funcionalidad: probablemente necesitas otro plugin/paquete (shape, interaccion, updater). -- Errores de tipos en opciones: manten tus paquetes alineados en la misma version major/minor. +- Documentación de opciones: [`/options/`](/es/options/) +- Guía de bundles: [`/guide/bundles`](/es/guide/bundles) +- Catálogo de presets: [`/demos/presets`](/es/demos/presets) +- Catálogo de paletas: [`/demos/palettes`](/es/demos/palettes) +- Catálogo de formas: [`/demos/shapes`](/es/demos/shapes) +- Wrappers para frameworks: [`/guide/wrappers`](/es/guide/wrappers) +- Formatos de color: [`/guide/color-formats`](/es/guide/color-formats) +- Ciclo de vida del contenedor: [`/guide/container-lifecycle`](/es/guide/container-lifecycle) +- Plugins y personalización: [`/guide/plugins-customization`](/es/guide/plugins-customization) + +## Solución de problemas + +| Problema | Causa probable | Solución | +| ----------------------------------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | +| Pantalla en blanco, sin partículas | `#tsparticles` no existe en el DOM cuando llamas `tsParticles.load()` | Verifica que el DIV esté presente antes del script, o usa `DOMContentLoaded` | +| Pantalla en blanco, sin partículas | Has instalado solo `@tsparticles/engine` | Debes instalar también un bundle (`@tsparticles/slim`) o plugins, porque el engine solo no tiene formas que dibujar | +| Error "loadBasic/loadSlim/loadFull is not a function" | Bundle no instalado o import incorrecto | `pnpm add @tsparticles/slim` e importa `{ loadSlim }` | +| Las partículas no se mueven | `move.enable` no está establecido a `true` | Añade `move: { enable: true, speed: 2 }` | +| Funcionalidad faltante (ej. enlaces, colisiones) | El bundle elegido no incluye esa funcionalidad | Cambia a un bundle más completo (`@tsparticles/slim` o `tsparticles`) o instala el plugin específico | +| Errores de tipo TypeScript | Versiones de los paquetes no alineadas | Mantén engine y bundle en la misma versión mayor/menor | diff --git a/websites/website/docs/es/guide/installation.md b/websites/website/docs/es/guide/installation.md index 77f64b96ce3..99abebd344e 100644 --- a/websites/website/docs/es/guide/installation.md +++ b/websites/website/docs/es/guide/installation.md @@ -1,109 +1,147 @@ -# Instalacion - -Esta pagina replica la matriz de instalacion del README principal de `tsParticles`. - -Referencia oficial: +# Instalación ## Elige tu ruta -- **Inicio rapido**: `@tsparticles/engine` + `@tsparticles/slim` -- **Runtime personalizado mas ligero**: `@tsparticles/engine` + solo los plugins necesarios -- **APIs enfocadas**: `@tsparticles/particles`, `@tsparticles/confetti`, `@tsparticles/fireworks` o `@tsparticles/ribbons` -- **Todas las funcionalidades incluidas**: `@tsparticles/all` - -## Hosting / CDN - -Usa uno de estos proveedores (o autoalojar tus archivos generados). +| Escenario | Comando | +| ------------------------------------ | ------------------------------------------------- | +| Inicio rápido (recomendado) | `pnpm add @tsparticles/engine @tsparticles/slim` | +| Mínimo indispensable | `pnpm add @tsparticles/engine @tsparticles/basic` | +| Conjunto completo de funcionalidades | `pnpm add @tsparticles/engine tsparticles` | +| Todo el ecosistema | `pnpm add @tsparticles/engine @tsparticles/all` | +| Solo confeti | `pnpm add @tsparticles/confetti` | +| Solo fuegos artificiales | `pnpm add @tsparticles/fireworks` | +| Fondo de partículas | `pnpm add @tsparticles/particles` | +| Efecto ribbon | `pnpm add @tsparticles/ribbons` | -### jsDelivr +> **Importante**: `@tsparticles/engine` por sí solo no dibuja nada. Debes añadir siempre un bundle (para cargar formas y animaciones) o plugins individuales. Ver la [guía de bundles](/es/guide/bundles). -- -- -- -- -- -- -- -- +## Con npm -### cdnjs +```bash +# engine + slim (recomendado para la mayoría de proyectos) +npm install @tsparticles/engine @tsparticles/slim -- +# engine + basic (mínimo) +npm install @tsparticles/engine @tsparticles/basic -### unpkg +# engine + full (tsparticles) +npm install @tsparticles/engine tsparticles -- -- -- -- -- -- -- -- +# engine + all (todo) +npm install @tsparticles/engine @tsparticles/all -## Instalacion con package manager +# Bundle con API dedicada (no necesita engine explícito) +npm install @tsparticles/confetti +npm install @tsparticles/fireworks +npm install @tsparticles/particles +npm install @tsparticles/ribbons +``` -### npm +## Con yarn ```bash -npm install @tsparticles/engine +yarn add @tsparticles/engine @tsparticles/slim +# ... mismo esquema que los otros bundles ``` -### yarn +## Con pnpm ```bash -yarn add @tsparticles/engine +pnpm add @tsparticles/engine @tsparticles/slim +# ... mismo esquema que los otros bundles ``` -### pnpm +## Con CDN (etiqueta ` + + + + +``` -- [`/guide/getting-started`](/es/guide/getting-started) -- [`/guide/wrappers`](/es/guide/wrappers) -- [`/demos/presets`](/es/demos/presets) -- [`/migrations/particles-js`](/es/migrations/particles-js) +Con los bundles de API dedicada: -## Compatibilidad legacy +```html + + +``` -Si estas migrando integraciones antiguas de particles.js, usa el paquete de compatibilidad: +## Páginas relacionadas -- npm: -- jsDelivr: +- [Primeros pasos](/es/guide/getting-started) +- [Guía de bundles](/es/guide/bundles) +- [Catálogo de presets](/demos/presets) +- [Wrappers para frameworks](/es/guide/wrappers) diff --git a/websites/website/docs/es/guides/angular.md b/websites/website/docs/es/guides/angular.md new file mode 100644 index 00000000000..bdaa2c5fb3d --- /dev/null +++ b/websites/website/docs/es/guides/angular.md @@ -0,0 +1,631 @@ +--- +title: Integración con Angular +description: Guía paso a paso para integrar tsParticles en aplicaciones Angular usando @tsparticles/angular. +--- + +# Integración con Angular + +El paquete `@tsparticles/angular` proporciona componentes, módulos y servicios de Angular para tsParticles. Esta guía cubre tanto el enfoque tradicional con `NgModule` como los componentes independientes (standalone) de Angular 17+. + +--- + +## Instalación + +```bash +npm install @tsparticles/angular @tsparticles/engine +``` + +Para el conjunto completo de funcionalidades, instala el paquete completo: + +```bash +npm install tsparticles +``` + +Paquetes de preset opcionales: + +```bash +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +``` + +--- + +## Uso Básico (NgModule) + +### 1. Importar el Módulo + +```typescript +import { NgModule } from "@angular/core"; +import { BrowserModule } from "@angular/platform-browser"; +import { NgParticlesModule } from "@tsparticles/angular"; +import { AppComponent } from "./app.component"; + +@NgModule({ + declarations: [AppComponent], + imports: [BrowserModule, NgParticlesModule], + bootstrap: [AppComponent], +}) +export class AppModule {} +``` + +### 2. Inicializar el Motor + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d47a1", + }, + fpsLimit: 120, + particles: { + number: { + value: 80, + }, + color: { + value: "#ffffff", + }, + shape: { + type: "circle", + }, + opacity: { + value: 0.5, + }, + size: { + value: { min: 1, max: 5 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Contenedor de partículas cargado", container); + } +} +``` + +### 3. Plantilla + +```html + +``` + +--- + +## Detalles de la Inicialización del Motor + +El método `NgParticlesService.init()` debe llamarse exactamente una vez, normalmente en `AppComponent.ngOnInit()`. Recibe un callback donde cargas los plugins/presets que tu aplicación necesita. + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesService } from "@tsparticles/angular"; +import type { Engine } from "@tsparticles/engine"; + +@Component({ ... }) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + // Carga solo lo que necesitas para paquetes más pequeños + await loadBasic(engine); // formas básicas + movimiento + await loadEmittersPlugin(engine); // formas de emisor + }); + } +} +``` + +Funciones de carga disponibles desde `tsparticles`: + +| Función | Descripción | +| ------------------- | --------------------------------------------------------------- | +| `loadFull(engine)` | Todas las funcionalidades (paquete más grande) | +| `loadBasic(engine)` | Formas básicas (círculo, cuadrado, polígono, etc.) | +| `loadSlim(engine)` | La mayoría de funcionalidades sin plugins de uso poco frecuente | +| `loadAll(engine)` | Alias obsoleto de `loadFull` | + +--- + +## Efecto Confeti + +```bash +npm install @tsparticles/preset-confetti +``` + +```typescript +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// En el callback de NgParticlesService.init: +await loadConfettiPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "confetti", + background: { + color: "transparent", + }, +}; +``` + +O usa el componente `` por comodidad: + +```typescript +// app.module.ts +import { NgParticlesModule } from "@tsparticles/angular"; + +@NgModule({ + imports: [NgParticlesModule], +}) +export class AppModule {} +``` + +```html + +``` + +--- + +## Efecto Fuegos Artificiales + +```bash +npm install @tsparticles/preset-fireworks +``` + +```typescript +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; + +// En el callback de NgParticlesService.init: +await loadFireworksPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "fireworks", + background: { + color: "#000000", + }, +}; +``` + +O usa el componente ``: + +```html + +``` + +> Evita iniciar automáticamente los fuegos artificiales; vincúlalos a una acción del usuario (clic, desplazamiento) para evitar el uso innecesario de recursos. + +--- + +## Configuración Personalizada de Partículas + +Configuración personalizada completa con interactividad: + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-particles", + templateUrl: "./particles.component.html", +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d0d0d", + }, + fpsLimit: 60, + particles: { + number: { + value: 100, + density: { + enable: true, + }, + }, + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + shape: { + type: ["circle", "square", "triangle"], + }, + opacity: { + value: 0.8, + random: true, + anim: { + enable: true, + speed: 1, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + random: true, + anim: { + enable: true, + speed: 4, + size_min: 1, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.3, + width: 1, + triangles: { + enable: true, + color: "#ffffff", + opacity: 0.05, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { + enable: true, + rotateX: 600, + rotateY: 600, + }, + }, + life: { + duration: { + value: 5, + random: true, + }, + count: 0, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: { + enable: true, + }, + }, + modes: { + grab: { + distance: 200, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + detectRetina: true, + }; + + particlesLoaded(container: Container): void { + console.log("Contenedor cargado", container); + } +} +``` + +```html + +``` + +--- + +## Eventos + +El componente `ngx-particles` emite el evento `particlesLoaded`: + +```typescript +import type { Container } from "@tsparticles/engine"; + +// Método del componente +onParticlesLoaded(container: Container): void { + // Accede a la API del contenedor + container.pause(); + container.play(); + container.destroy(); + container.exportImage().then((blob) => { /* ... */ }); +} +``` + +```html + +``` + +La referencia al contenedor te da control programático completo: pausar, reanudar, destruir, exportar y más. + +--- + +## Sintaxis de Plantilla y Renderizado Condicional + +Usa directivas estructurales de Angular para alternar el componente: + +```html + + + +``` + +```typescript +export class AppComponent { + showParticles = true; + // ... +} +``` + +Cuando `*ngIf` evalúa a `false`, el componente se destruye (incluyendo el canvas y todas las instancias de partículas). Volver a crearlo reinicia todo desde cero. + +--- + +## Componentes Independientes (Angular 17+) + +En Angular 17+, puedes importar `NgParticlesModule` directamente en un componente independiente: + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesModule, NgParticlesService } from "@tsparticles/angular"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +@Component({ + selector: "app-particles", + standalone: true, + imports: [NgParticlesModule], + template: ` + + `, +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 50 }, + color: { value: "#fff" }, + shape: { type: "circle" }, + move: { enable: true, speed: 2 }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Cargado", container); + } +} +``` + +No se necesita envoltorio `NgModule` — solo importa `NgParticlesModule` en el arreglo `imports` del componente. + +--- + +## Ejemplo de Componente Completo + +### app.component.ts + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + title = "tsParticles Angular Demo"; + + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadSlim(engine); + }); + } + + particlesOptions: ISourceOptions = { + autoPlay: true, + background: { + color: "#1e1e2e", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMask: { + cover: { + color: "#1e1e2e", + }, + enable: false, + }, + fullScreen: { + enable: true, + zIndex: -1, + }, + detectRetina: true, + fpsLimit: 60, + particles: { + color: { + value: "#cdd6f4", + }, + links: { + color: "#cdd6f4", + distance: 150, + enable: true, + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1, + }, + number: { + value: 60, + }, + opacity: { + value: 0.6, + }, + size: { + value: { min: 1, max: 3 }, + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Partículas cargadas", container); + } +} +``` + +### app.component.html + +```html +
+ + +
+

{{ title }}

+

Las partículas se están ejecutando en segundo plano.

+
+
+``` + +### app.component.css + +```css +:host { + display: block; + width: 100%; + height: 100%; +} +``` + +--- + +## Referencia de API + +| Componente | Selector | Descripción | +| ---------- | --------------- | --------------------------------------------- | +| Particles | `ngx-particles` | Componente completo del sistema de partículas | +| Confetti | `ngx-confetti` | Efecto de confeti preconfigurado | +| Fireworks | `ngx-fireworks` | Efecto de fuegos artificiales preconfigurado | + +### Entradas de `ngx-particles` + +| Entrada | Tipo | Por Defecto | Descripción | +| --------- | ---------------- | --------------- | -------------------------------- | +| `id` | `string` | `"tsparticles"` | ID del elemento canvas | +| `options` | `ISourceOptions` | `{}` | Configuración de partículas | +| `url` | `string` | — | URL remota de configuración JSON | + +### Salidas de `ngx-particles` + +| Salida | Carga | Descripción | +| ----------------- | ----------- | ------------------------------------------- | +| `particlesLoaded` | `Container` | Se emite cuando el contenedor se inicializa | + +--- + +## Solución de Problemas + +- **Canvas en blanco / invisible** — Asegúrate de que el elemento padre tenga una altura definida (ej., `height: 100vh`). El canvas toma las dimensiones del contenedor. +- **`NgParticlesService.init()` llamado múltiples veces** — Llámalo solo una vez, normalmente en `AppComponent.ngOnInit()`. Las llamadas posteriores son seguras pero redundantes. +- **Módulo no encontrado** — Verifica que `@tsparticles/angular` esté listado en las dependencias de `package.json` y que hayas importado `NgParticlesModule`. +- **`NullInjectorError: No provider for NgParticlesService`** — Debes importar `NgParticlesModule` (o reexportarlo) en el módulo donde proporcionas el componente. diff --git a/websites/website/docs/es/guides/astro.md b/websites/website/docs/es/guides/astro.md new file mode 100644 index 00000000000..0eda59b744a --- /dev/null +++ b/websites/website/docs/es/guides/astro.md @@ -0,0 +1,384 @@ +# Integración con Astro + +Usa tsParticles en tu sitio Astro con el paquete de integración oficial `@tsparticles/astro`. + +## Instalación + +Instala la integración de Astro y el núcleo de tsParticles a través de tu gestor de paquetes: + +```bash +npm install @tsparticles/astro tsparticles +``` + +```bash +pnpm add @tsparticles/astro tsparticles +``` + +```bash +yarn add @tsparticles/astro tsparticles +``` + +## Inicialización del Motor + +tsParticles utiliza una arquitectura modular. Antes de renderizar partículas, debes inicializar el motor con las funcionalidades que necesitas. Crea un script de cliente (ej., `src/scripts/particles-init.ts`) o usa un ` +``` + +> La propiedad `id` se pasa al `
` contenedor del canvas subyacente. Úsalo para estilos o acceso imperativo mediante `document.getElementById()`. + +## Soporte TypeScript + +La integración incluye declaraciones TypeScript completas. Usa `ISourceOptions` de `@tsparticles/engine` para tipar tu configuración: + +```typescript +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { + value: 50, + density: { enable: true }, + }, + opacity: { value: 0.5 }, + shape: { type: "circle" }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + repulse: { distance: 200 }, + }, + }, +}; +``` + +## Configuración Personalizada + +A continuación se muestra una configuración más elaborada que puedes usar en cualquier página de Astro: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + autoPlay: true, + background: { + color: "#0d47a1", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMode: { + enable: true, + zIndex: -1, + }, + fpsLimit: 120, + particles: { + color: { + value: "#ffffff", + animation: { + enable: true, + speed: 20, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + triangles: { + enable: true, + opacity: 0.1, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "out", + attract: { enable: false }, + }, + number: { + value: 80, + density: { + enable: true, + }, + }, + opacity: { + value: 0.5, + animation: { + enable: true, + speed: 1, + sync: false, + }, + }, + shape: { + type: "circle", + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 3, + sync: false, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: true, + }, + modes: { + grab: { + distance: 200, + links: { opacity: 0.5 }, + }, + push: { quantity: 4 }, + }, + }, + detectRetina: true, +}; +--- + + + + +``` + +## Usando Presets + +En lugar de construir una configuración manualmente, carga un preset durante la inicialización del motor y haz referencia a él en las opciones: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + preset: "stars", + background: { color: "#000000" }, +}; +--- + + + + +``` + +## Integración con Otros Frameworks + +Debido a que Astro soporta frameworks de UI como React, Vue, Svelte y Solid, puedes usar el componente tsParticles específico del framework dentro de archivos `.astro`: + +### React en Astro + +```astro +--- +import Particles from "@tsparticles/react"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +### Vue en Astro + +```astro +--- +import Particles from "@tsparticles/vue3"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +> La directiva `client:load` le indica a Astro que hidrate el componente inmediatamente al cargar la página. Usa `client:visible` para carga diferida. + +## Ejemplo de Página Completa + +Una página Astro completa con partículas que sirven como fondo animado: + +```astro +--- +import Layout from "../layouts/Layout.astro"; +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + number: { value: 100 }, + color: { value: "#ffffff" }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + size: { + value: { min: 1, max: 4 }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, +}; +--- + + +
+

Bienvenido

+

Esta página tiene un fondo de partículas impulsado por tsParticles.

+
+ +
+ + + + +``` + +## Propiedades del Componente + +| Propiedad | Tipo | Por Defecto | Descripción | +| -------------------- | ---------------- | ------------------------- | ------------------------------------------------ | +| `id` | `string` | `"tsparticles"` | ID del elemento DOM para el contenedor | +| `options` | `ISourceOptions` | `{}` | Objeto completo de configuración de tsParticles | +| `url` | `string` | — | Cargar configuración desde una URL JSON remota | +| `particlesClassName` | `string` | `"tsparticles-canvas-el"` | Clase CSS para el elemento canvas | +| `container` | `object` | — | Instancia de `Container` preexistente (avanzado) | diff --git a/websites/website/docs/es/guides/ember.md b/websites/website/docs/es/guides/ember.md new file mode 100644 index 00000000000..ea7cc64342c --- /dev/null +++ b/websites/website/docs/es/guides/ember.md @@ -0,0 +1,346 @@ +--- +title: Guía de Ember +description: Guía completa para integrar tsParticles con aplicaciones Ember.js. +--- + +# Guía de Ember + +## Tabla de Contenidos + +1. [Instalación](#instalación) +2. [Inicialización del Motor](#inicialización-del-motor) +3. [Uso Básico](#uso-básico) +4. [Configuración Personalizada](#configuración-personalizada) +5. [Manejo de Eventos](#manejo-de-eventos) +6. [Renderizado Condicional](#renderizado-condicional) +7. [Ejemplo TypeScript](#ejemplo-typescript) + +--- + +## Instalación + +Instala el addon de Ember y el motor tsParticles a través de ember-cli: + +```bash +ember install @tsparticles/ember +``` + +Esto instalará el addon y su dependencia pares `tsparticles`. Opcionalmente puedes añadir paquetes de preset: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Inicialización del Motor + +El addon exporta una utilidad `initParticlesEngine` que llamas una vez a nivel de aplicación. Recibe un callback asíncrono donde cargas las funcionalidades, presets o formas que tu app necesita. + +```typescript +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadFull } from "tsparticles"; + +// Llama esto durante el arranque de la aplicación +if (typeof window !== "undefined") { + void initParticlesEngine(async (engine) => { + await loadFull(engine); + }); +} +``` + +Las ubicaciones típicas para esta llamada son el hook `beforeModel` de la ruta de la aplicación, el constructor de un controlador de aplicación, o un inicializador de instancia. El singleton del motor se inicializa una vez y se comparte entre todos los componentes `` en tu aplicación. + +--- + +## Uso Básico + +Después de inicializar el motor, usa el componente `` en cualquier plantilla. Pasa tu configuración de partículas a través del argumento `@options`. + +```hbs +{{! app/templates/application.hbs }} + + +``` + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, + }; +} +``` + +--- + +## Configuración Personalizada + +Construye una configuración más rica con interactividad, múltiples formas y densidad adaptable. + +```typescript +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class IndexController extends Controller { + options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, + }; +} +``` + +```hbs + +``` + +--- + +## Manejo de Eventos + +El componente `` dispara una acción `@particlesLoaded` cuando el contenedor ha terminado de inicializarse y el primer frame se ha renderizado. Úsalo para acceder a la instancia de `Container` para control programático. + +```typescript +import Controller from "@ember/controller"; +import { action } from "@ember/object"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + /* ... */ + }; + + @action + loadedCallback(container: Container) { + console.log("Partículas cargadas", container.id); + + // Ejemplo de control programático: + setTimeout(() => { + container.pause(); + console.log("Partículas pausadas después de 5 segundos"); + }, 5000); + } +} +``` + +```hbs + +``` + +También puedes usar el patrón de callback en línea con un helper de plantilla si prefieres no definir una acción separada. + +--- + +## Renderizado Condicional + +Usa el helper `{{if}}` de Ember junto con una propiedad `@tracked` para controlar cuándo se renderiza el componente ``. Esto es útil cuando la inicialización del motor es asíncrona y quieres evitar renderizar el componente antes de que el motor esté listo. + +```typescript +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked engineReady = false; + + options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { enable: true, speed: 1, outModes: { default: "bounce" } }, + }, + background: { color: "#1a1a2e" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } +} +``` + +```hbs +{{#if this.engineReady}} + +{{else}} +

Cargando partículas...

+{{/if}} +``` + +El decorador `@tracked` asegura que la plantilla se vuelva a renderizar automáticamente una vez que la promesa se resuelve. + +--- + +## Ejemplo TypeScript + +A continuación se muestra un controlador de aplicación Ember tipado completo que demuestra el patrón de integración completo con preset slim, interactividad y gestión del ciclo de vida. + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked private engineReady = false; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } + + @action + private handleParticlesLoaded(container: Container): void { + this.container = container; + console.log("Partículas cargadas en el contenedor:", container.id); + } +} +``` + +```hbs +{{! app/templates/application.hbs }} + +{{#if this.engineReady}} +
+

tsParticles + Ember

+ +
+{{else}} +
+

Inicializando el motor de partículas...

+
+{{/if}} +``` + +--- + +Ahora tienes todo lo necesario para integrar tsParticles en una aplicación Ember.js. Cada ejemplo es autónomo y está listo para copiar en tu proyecto. diff --git a/websites/website/docs/es/guides/index.md b/websites/website/docs/es/guides/index.md new file mode 100644 index 00000000000..ace0d8f1e52 --- /dev/null +++ b/websites/website/docs/es/guides/index.md @@ -0,0 +1,58 @@ +--- +title: Guías Paso a Paso +description: Explora guías específicas para frameworks para integrar tsParticles en tu proyecto. +--- + +# Guías Paso a Paso + +Bienvenido a la sección de guías de tsParticles. Ya sea que estés construyendo un sitio estático con Vanilla JS, una aplicación de una sola página en React o Vue, o una aplicación full-stack con Next.js o Nuxt, estos tutoriales paso a paso te guiarán en la instalación, el uso básico, las configuraciones avanzadas y los efectos interactivos. + +Cada guía es autónoma e incluye ejemplos de código listos para copiar y pegar para que puedas empezar rápidamente. + +## Guías Disponibles + +| Framework / Wrapper | Paquete | Descripción | +| --------------------------------- | ------------------------------------------ | ----------------------------------------------------------- | +| [Vanilla JS](./vanilla) | `tsparticles` (CDN o npm) | Integración directa con DOM usando `tsParticles.load()` | +| [React](./react) | `@tsparticles/react` | Wrapper oficial de React con hooks y API de componentes | +| [Vue 3](./vue3) | `@tsparticles/vue3` | Plugin oficial de Vue 3 con composables | +| [Angular](./angular) | `@tsparticles/angular` | Componente y módulo oficial de Angular | +| [Svelte](./svelte) | `@tsparticles/svelte` | Componente oficial de Svelte | +| [Next.js](./nextjs) | `@tsparticles/react` (con Next.js) | Renderizado del lado del servidor e importaciones dinámicas | +| [Nuxt](./nuxt) | `@tsparticles/vue3` (con Nuxt) | Integración segura para SSR como plugin de Nuxt | +| [Solid](./solid) | `@tsparticles/solid` | Wrapper oficial de SolidJS | +| [Preact](./preact) | `@tsparticles/preact` | Componente compatible con Preact | +| [Lit](./lit) | `@tsparticles/lit` | Wrapper de componente web Lit | +| [Qwik](./qwik) | `@tsparticles/qwik` | Integración optimizada para Qwik | +| [jQuery](./jquery) | `@tsparticles/jquery` | Plugin de jQuery para proyectos heredados | +| [Astro](./astro) | `@tsparticles/react` (o cualquier wrapper) | Arquitectura de islas con directivas de cliente | +| [Web Components](./webcomponents) | `@tsparticles/webcomponents` | Integración con API de Custom Elements | +| [Stencil](./stencil) | `@tsparticles/stencil` | Wrapper de componente Stencil | +| [Ember](./ember) | `@tsparticles/ember` | Integración como addon de Ember | +| [Riot](./riot) | `@tsparticles/riot` | Wrapper de Riot.js | +| [Inferno](./inferno) | `@tsparticles/inferno` | Componente compatible con Inferno | +| [WordPress](./wordpress) | Plugin + `tsparticles` | Integración con editor de bloques / shortcode | + +## Elige tu Guía + +- [Vanilla JS (JavaScript plano)](./vanilla) +- [React](./react) +- [Vue 3](./vue3) +- [Angular](./angular) +- [Svelte](./svelte) +- [Next.js](./nextjs) +- [Nuxt](./nuxt) +- [Solid](./solid) +- [Preact](./preact) +- [Lit](./lit) +- [Qwik](./qwik) +- [jQuery](./jquery) +- [Astro](./astro) +- [Web Components](./webcomponents) +- [Stencil](./stencil) +- [Ember](./ember) +- [Riot](./riot) +- [Inferno](./inferno) +- [WordPress](./wordpress) + +¡Feliz construcción! diff --git a/websites/website/docs/es/guides/inferno.md b/websites/website/docs/es/guides/inferno.md new file mode 100644 index 00000000000..91fda6c6d62 --- /dev/null +++ b/websites/website/docs/es/guides/inferno.md @@ -0,0 +1,373 @@ +--- +title: Guía de Inferno +description: Guía completa para integrar tsParticles con aplicaciones Inferno. +--- + +# Guía de Inferno + +## Tabla de Contenidos + +1. [Instalación](#instalación) +2. [Uso Básico](#uso-básico) +3. [Inicialización del Motor](#inicialización-del-motor) +4. [Configuración Personalizada](#configuración-personalizada) +5. [Uso de Presets](#uso-de-presets) +6. [Patrón de Componente](#patrón-de-componente) +7. [Ejemplo TypeScript](#ejemplo-typescript) + +--- + +## Instalación + +Instala el wrapper de Inferno y el motor tsParticles a través de npm: + +```bash +npm install @tsparticles/inferno tsparticles +``` + +Opcionalmente instala el preset slim para un paquete más pequeño: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Uso Básico + +El paquete `@tsparticles/inferno` exporta dos elementos: `ParticlesProvider` y `Particles`. Envuelve tus componentes de partículas con `ParticlesProvider` que acepta un callback `init` para la configuración del motor, luego usa `` para renderizar el canvas de partículas. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import { loadSlim } from "@tsparticles/slim"; + +const options = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +function App() { + return ( + { + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +`ParticlesProvider` debe ser un ancestro de cada componente ``. Inicializa el motor una vez y lo proporciona a través del contexto a todos los hijos. + +--- + +## Inicialización del Motor + +El `ParticlesProvider` acepta una propiedad `init` que recibe la instancia del motor. Aquí es donde cargas las funcionalidades, formas, presets o actualizadores que tu aplicación necesita. + +```tsx +// Ligero — partículas circulares, movimiento básico, enlaces + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); +}}> + +// Conjunto completo de funcionalidades — todas las formas, interacciones, efectos + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); +}}> + +// Preset específico — confeti, fuegos artificiales, nieve, estrellas + { + const { loadConfettiPreset } = await import("@tsparticles/preset-confetti"); + await loadConfettiPreset(engine); +}}> +``` + +Usar `import()` dinámico dentro del callback permite la división de código: los módulos de preset o funcionalidades se cargan solo cuando el componente de partículas se monta. + +--- + +## Configuración Personalizada + +A continuación se muestra una configuración completa con interactividad, múltiples tipos de formas y un fondo degradado oscuro. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, +}; + +function App() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +--- + +## Uso de Presets + +El paquete `@tsparticles/configs` ofrece configuraciones preconstruidas que puedes pasar directamente a la propiedad `options`. Combínalas con el cargador de preset correspondiente en el callback `init` de `ParticlesProvider`. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import configs from "@tsparticles/configs"; + +function App() { + return ( + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +Puedes cambiar `configs.confetti` por cualquier preset disponible: `configs.basic`, `configs.fireworks`, `configs.snow`, `configs.stars`, etc. + +--- + +## Patrón de Componente + +Para aplicaciones más grandes, estructura tu lógica de partículas en un componente dedicado con un callback `particlesLoaded` para acceder a la instancia de `Container`. + +```tsx +import { render, Component } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +class ParticlesBackground extends Component { + private container?: Container; + + handleParticlesLoaded(container?: Container) { + this.container = container; + console.log("Partículas cargadas:", container?.id); + } + + render() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); + } +} + +function App() { + return ( +
+

tsParticles + Inferno

+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +## Ejemplo TypeScript + +Aquí hay una aplicación Inferno completa y tipada con una configuración de partículas adaptable y fondo de pantalla completa. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const particlesOptions: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +function handleInit(engine: Engine): Promise { + return import("@tsparticles/slim").then(({ loadSlim }) => loadSlim(engine)); +} + +function handleParticlesLoaded(container?: Container): void { + console.log("Contenedor de tsParticles listo:", container?.id); +} + +function App() { + return ( + +
+

tsParticles + Inferno

+

Integración completa TypeScript

+
+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +Ahora tienes todo lo necesario para integrar tsParticles en una aplicación Inferno. Cada ejemplo es autónomo y está listo para copiar en tu proyecto. diff --git a/websites/website/docs/es/guides/jquery.md b/websites/website/docs/es/guides/jquery.md new file mode 100644 index 00000000000..07abb8f6619 --- /dev/null +++ b/websites/website/docs/es/guides/jquery.md @@ -0,0 +1,274 @@ +# Integración con jQuery + +Integra tsParticles en tus proyectos basados en jQuery con el wrapper oficial del plugin jQuery. + +## Instalación + +### Vía CDN + +Incluye jQuery, tsParticles y el plugin jQuery a través de etiquetas script: + +```html + + + +``` + +--- + +### Vía npm + Build + +Instala los paquetes necesarios: + +```bash +npm install jquery @tsparticles/jquery tsparticles +``` + +Importa en tu proyecto: + +```javascript +import $ from "jquery"; +import "@tsparticles/jquery"; +``` + +## Inicialización del Motor + +Antes de que las partículas puedan renderizarse, el motor tsParticles debe ser inicializado con las funcionalidades que necesitas. Esto se hace a través de `$.particles.init`: + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); +})(); +``` + +> **¿Por qué es necesario?** tsParticles utiliza una arquitectura modular. `loadFull` registra todas las formas, interacciones y actualizadores incorporados. Puedes importar paquetes más pequeños (ej., `tsparticles-slim`) para reducir el tamaño del paquete. + +## Uso Básico + +Una vez que el motor está inicializado y el DOM está listo, selecciona un elemento contenedor y llama a `.particles().load()`: + +```javascript +$(document).ready(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); + + $("#tsparticles") + .particles() + .load({ + background: { + color: "#0d47a1", + }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + }, + }); +}); +``` + +El elemento contenedor debe existir en el DOM: + +```html +
+``` + +## Configuración Personalizada + +El método `.load()` acepta el objeto `ISourceOptions` completo. Aquí hay un ejemplo completo: + +```javascript +$("#tsparticles") + .particles() + .load({ + background: { + color: "#000000", + }, + fpsLimit: 120, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + direction: "none", + enable: true, + outModes: "bounce", + speed: 4, + }, + number: { + density: { + enable: true, + }, + value: 60, + }, + opacity: { + value: 0.6, + }, + shape: { + type: ["circle", "square", "triangle"], + }, + size: { + value: { min: 2, max: 8 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + }, + interactivity: { + events: { + onClick: { + enable: true, + mode: "push", + }, + onHover: { + enable: true, + mode: "repulse", + }, + }, + modes: { + push: { + quantity: 4, + }, + repulse: { + distance: 200, + }, + }, + }, + }); +``` + +## Carga de Presets + +Si has instalado un paquete de preset (ej. `tsparticles-preset-stars`), cárgalo durante la inicialización del motor y haz referencia a él en la configuración: + +```bash +npm install tsparticles-preset-stars +``` + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadStarsPreset } = await import("tsparticles-preset-stars"); + await loadStarsPreset(engine); + }); + + $("#tsparticles") + .particles() + .load({ + preset: "stars", + background: { color: "#0d47a1" }, + }); +})(); +``` + +## Manejo de Eventos y Control del Contenedor + +`.particles()` devuelve una instancia del plugin jQuery. Para acceder al `Container` subyacente de tsParticles y llamar a métodos como `play()`, `pause()` o `destroy()`: + +```javascript +const $container = $("#tsparticles"); + +// Cargar partículas +$container.particles().load({ + /* opciones */ +}); + +// Reproducir/pausar después de unos segundos +setTimeout(() => { + const container = $container.particles().getContainer(); + container?.pause(); +}, 5000); +``` + +## Ejemplo Completo + +A continuación se muestra una página HTML completa y autónoma que carga tsParticles vía CDN y renderiza una escena de partículas con efectos interactivos: + +```html + + + + + + tsParticles + jQuery + + + +
+ + + + + + + +``` + +## Referencia de API + +| Método | Descripción | +| ---------------------------------- | ---------------------------------------------------------- | +| `$.particles.init(fn)` | Inicializa el motor con un callback de carga | +| `$(el).particles()` | Crea una instancia del plugin de partículas en el elemento | +| `$(el).particles().load(opts)` | Carga e inicia la configuración de partículas | +| `$(el).particles().destroy()` | Destruye la instancia de partículas y limpia | +| `$(el).particles().getContainer()` | Devuelve el `Container` subyacente para control imperativo | diff --git a/websites/website/docs/es/guides/lit.md b/websites/website/docs/es/guides/lit.md new file mode 100644 index 00000000000..d6b4a74ee79 --- /dev/null +++ b/websites/website/docs/es/guides/lit.md @@ -0,0 +1,301 @@ +--- +title: Lit +description: Integra tsParticles con Lit usando el wrapper oficial de componente web @tsparticles/lit. +--- + +# Integración con Lit + +El paquete `@tsparticles/lit` proporciona un elemento personalizado `` construido con Lit, permitiéndote usar tsParticles de forma declarativa en cualquier proyecto Lit o página HTML plana. + +## Instalación + +```bash +npm install @tsparticles/lit tsparticles +``` + +El paquete está completamente tipado e incluye los patrones de controlador reactivo de Lit para actualizar reactivamente las opciones de partículas. + +## Inicialización del Motor + +Llama a `initParticlesEngine` antes de registrar el componente `` o importarlo en tu aplicación. Esto debe ocurrir exactamente una vez. + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadFull } from "tsparticles"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +Para tamaños de paquete optimizados, importa solo las funcionalidades que tu proyecto necesita: + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadBasic } from "@tsparticles/basic"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +void initParticlesEngine(async (engine) => { + await loadBasic(engine); + await loadConfettiPreset(engine); +}); +``` + +## Uso Básico + +Después de inicializar el motor, usa el elemento `` en cualquier plantilla Lit o archivo HTML: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private options = { + background: { + color: "#0d1117", + }, + particles: { + number: { value: 60 }, + color: { value: "#58a6ff" }, + links: { + enable: true, + color: "#58a6ff", + }, + move: { enable: true, speed: 2 }, + }, + }; + + render() { + return html` `; + } +} +``` + +La sintaxis `.options` (con punto inicial) es el enlace de propiedades de Lit, asegurando que el objeto se pase por referencia en lugar de serializarse como atributo. + +## Uso en HTML Plano + +Una vez que `@tsparticles/lit` está empaquetado o cargado, el elemento funciona también en HTML plano: + +```html + + + + + + + + + +``` + +Puedes pasar un objeto de opciones mínimo como atributo JSON: + +```html + +``` + +## Configuración Personalizada + +Pasa una configuración completa de tsParticles como propiedad de Lit: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-particles") +class MyParticles extends LitElement { + @property({ type: Object }) + options: ISourceOptions = { + background: { + color: "#0d1117", + }, + fpsLimit: 120, + fullScreen: { + enable: true, + zIndex: -1, + }, + particles: { + color: { + value: ["#ff5733", "#33ff57", "#3357ff"], + }, + links: { + color: "#ffffff", + enable: true, + opacity: 0.3, + distance: 150, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + }, + number: { + value: 100, + density: { + enable: true, + }, + }, + opacity: { + value: 0.6, + animation: { + enable: true, + speed: 0.5, + minimumValue: 0.1, + }, + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 2, + minimumValue: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + }, + modes: { + grab: { + distance: 180, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + }; + + render() { + return html` `; + } +} +``` + +## Manejo de Eventos + +Escucha el evento personalizado `particles-loaded` emitido por el elemento ``: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import type { Container } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private handleParticlesLoaded(e: CustomEvent) { + const container = e.detail; + console.log("Partículas cargadas:", container); + container?.refresh(); + } + + render() { + return html` `; + } +} +``` + +## Ejemplo TypeScript + +Un elemento Lit completamente tipado con `initParticlesEngine`, opciones reactivas y manejo de eventos: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import { initParticlesEngine } from "@tsparticles/lit"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import "@tsparticles/lit"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +@customElement("particles-background") +class ParticlesBackground extends LitElement { + @property({ type: Object }) + options: ISourceOptions = {}; + + @property({ type: Boolean, attribute: "fullscreen" }) + fullscreen = true; + + protected onParticlesLoaded(e: CustomEvent) { + console.log("Contenedor listo:", e.detail.id); + } + + render() { + return html` + + + `; + } +} +``` + +## Actualizaciones Dinámicas + +Debido a que `` usa las propiedades reactivas de Lit, cambiar la propiedad `options` actualiza automáticamente las partículas: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("dynamic-particles") +class DynamicParticles extends LitElement { + @state() + private theme: "light" | "dark" = "dark"; + + private get options(): ISourceOptions { + return this.theme === "dark" + ? { + background: { color: "#0d1117" }, + particles: { color: { value: "#58a6ff" } }, + } + : { + background: { color: "#ffffff" }, + particles: { color: { value: "#0969da" } }, + }; + } + + private toggleTheme() { + this.theme = this.theme === "dark" ? "light" : "dark"; + } + + render() { + return html` + + + `; + } +} +``` + +El componente observa la propiedad `options` y llama a `refresh()` internamente cada vez que cambia, actualizando sin problemas la configuración de partículas en tiempo de ejecución. diff --git a/websites/website/docs/es/guides/nextjs.md b/websites/website/docs/es/guides/nextjs.md new file mode 100644 index 00000000000..1a9982a6334 --- /dev/null +++ b/websites/website/docs/es/guides/nextjs.md @@ -0,0 +1,492 @@ +--- +title: Integración con Next.js +description: Guía paso a paso para integrar tsParticles en una aplicación Next.js usando el App Router. +--- + +# Integración con Next.js + +Esta guía cubre la integración de tsParticles en un proyecto Next.js usando el **App Router** (Next.js 13+). Para el Pages Router heredado, consulta la sección [Pages Router Heredado](#pages-router-heredado) al final. + +## Instalación + +Instala el wrapper `@tsparticles/react` y el motor completo `tsparticles` (o un paquete slim para builds más pequeños): + +```bash +npm install @tsparticles/react tsparticles +``` + +Si prefieres el paquete más pequeño `@tsparticles/slim`: + +```bash +npm install @tsparticles/react @tsparticles/slim +``` + +## Uso Básico (App Router) + +Los componentes del App Router de Next.js son del lado del servidor por defecto. Dado que tsParticles requiere la API `canvas` del navegador, debes marcar el componente con la directiva `"use client"`. + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesBackground() { + const particlesLoaded = useCallback((container?: Container) => { + console.log("Partículas cargadas", container); + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }), + [], + ); + + return ; +} +``` + +Crea esto como `components/particles-background.tsx` e impórtalo en cualquier página o layout. Como el archivo comienza con `"use client"`, se renderizará en el cliente — exactamente donde tsParticles necesita estar. + +## Cambio de Tema + +Combina tsParticles con alternadores de tema de Next.js derivando las opciones del estado actual del tema: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useMemo, useState, useCallback } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ThemeAwareParticles() { + const [theme, setTheme] = useState<"light" | "dark">("dark"); + + const toggleTheme = useCallback(() => { + setTheme((t) => (t === "dark" ? "light" : "dark")); + }, []); + + const particlesLoaded = useCallback((_container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { + color: theme === "dark" ? "#000000" : "#ffffff", + }, + particles: { + color: { value: theme === "dark" ? "#ffffff" : "#000000" }, + number: { value: 100 }, + links: { + enable: true, + color: theme === "dark" ? "#ffffff" : "#000000", + }, + move: { enable: true }, + }, + }), + [theme], + ); + + return ( + <> + + + + ); +} +``` + +El objeto `options` se recrea mediante `useMemo` cada vez que `theme` cambia, por lo que el canvas se actualiza automáticamente. + +## Efecto Confeti + +Usa el preset `@tsparticles/preset-confetti` para lanzar confeti de celebración en eventos como clics de botón: + +```bash +npm install @tsparticles/preset-confetti +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Container, ISourceOptions, Engine } from "@tsparticles/engine"; + +export default function ConfettiButton() { + const [active, setActive] = useState(false); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadConfettiPreset(engine); + }, []); + + const particlesLoaded = useCallback( + async (container?: Container) => { + if (active && container) { + await container.play(); + } + }, + [active], + ); + + const options: ISourceOptions = useMemo( + () => ({ + preset: "confetti", + fullScreen: { zIndex: 1000 }, + }), + [], + ); + + const handleCelebrate = useCallback(() => { + setActive(true); + setTimeout(() => setActive(false), 5000); + }, []); + + return ( + <> + {active && } + + + ); +} +``` + +El callback `init` carga el preset de confeti en el motor antes de que se creen las partículas. + +## Efecto Fuegos Artificiales + +Del mismo modo, el preset de fuegos artificiales crea un espectacular despliegue de fuegos artificiales: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; +import type { Container, Engine } from "@tsparticles/engine"; + +export default function FireworksBackground() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFireworksPreset(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options = useMemo( + () => ({ + preset: "fireworks" as const, + fullScreen: { zIndex: -1 }, + background: { + color: "#000", + }, + }), + [], + ); + + return ; +} +``` + +## Ejemplo TypeScript Completo con Referencia al Contenedor + +Accede a la instancia de `Container` para controlar la animación programáticamente (reproducir, pausar, destruir, exportar imagen): + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +export default function ControllableParticles() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFull(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + fpsLimit: 120, + interactivity: { + events: { + onClick: { enable: true, mode: "push" }, + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + push: { quantity: 4 }, + repulse: { distance: 100 }, + }, + }, + particles: { + color: { value: "#ff0000" }, + links: { + enable: true, + color: "#ff0000", + distance: 150, + }, + move: { enable: true, speed: 2 }, + number: { value: 60 }, + size: { value: { min: 1, max: 5 } }, + }, + }), + [], + ); + + const handlePause = useCallback(() => { + containerRef.current?.pause(); + }, []); + + const handlePlay = useCallback(() => { + containerRef.current?.play(); + }, []); + + return ( +
+ +
+ + +
+
+ ); +} +``` + +Puntos clave: + +- `particlesInit` carga las funcionalidades del motor (solo se ejecuta una vez por montaje del componente). +- `particlesLoaded` se dispara cada vez que el contenedor se inicializa completamente. +- `containerRef` mantiene la instancia de `Container` para que puedas llamar a sus métodos más tarde. + +## Rendimiento: useMemo y useCallback + +Siempre envuelve opciones estáticas o que cambian raramente en `useMemo` y los manejadores de eventos en `useCallback` para evitar renderizaciones innecesarias del canvas: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function PerformanceExample() { + const [particlesCount, setParticlesCount] = useState(80); + + // Callback estable — nunca se recrea a menos que las dependencias cambien + const particlesLoaded = useCallback((container?: Container) => { + console.log("Contenedor listo", container?.id); + }, []); + + // Objeto de opciones estable — evita la reinicialización del canvas + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: particlesCount }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [particlesCount], + ); + + return ( +
+ + +
+ ); +} +``` + +Sin estas optimizaciones, cada rerenderizado del padre crearía un nuevo objeto `options`, provocando que el canvas se recreara. + +## Integración en Páginas + +Añade un fondo de partículas a un layout de página sin afectar el contenido de la página: + +```tsx +// app/layout.tsx (componente servidor) +import dynamic from "next/dynamic"; + +const ParticlesBackground = dynamic(() => import("@/components/particles-background"), { ssr: false }); + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + +
{children}
+ + + ); +} +``` + +Usa `dynamic()` con `ssr: false` para asegurar que el componente nunca se ejecute durante el renderizado del lado del servidor. El canvas de partículas se sitúa detrás del contenido principal mediante CSS `z-index`. + +## Múltiples Instancias + +Puedes renderizar varios componentes `Particles` independientes en la misma página, cada uno con su propia configuración: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +function ParticlesGallery() { + const loaded = useCallback((c?: Container) => {}, []); + + const redOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#1a0000" }, + particles: { + color: { value: "#ff0000" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + const blueOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#00001a" }, + particles: { + color: { value: "#0000ff" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + return ( +
+ + +
+ ); +} +``` + +Cada componente `Particles` crea un canvas independiente con su propio bucle de animación. Establece `fullScreen: false` y asigna a cada uno una altura fija para que coexistan en el flujo del documento. + +## Pages Router Heredado + +Si estás usando el **Pages Router** de Next.js (directorio `pages/`), el enfoque es similar pero sin la directiva `"use client"`. En su lugar, puedes usar una importación dinámica en el componente de la página: + +```tsx +// pages/index.tsx +import dynamic from "next/dynamic"; +import type { NextPage } from "next"; + +const ParticlesComponent = dynamic(() => import("../components/particles-component"), { ssr: false }); + +const Home: NextPage = () => { + return ( +
+ +

Bienvenido

+
+ ); +}; + +export default Home; +``` + +El componente en sí (`components/particles-component.tsx`) es un componente React normal: + +```tsx +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesComponent() { + const particlesLoaded = useCallback((container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 80 }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [], + ); + + return ; +} +``` + +Ten en cuenta que el Pages Router **no** requiere `"use client"` porque los componentes de página ya se renderizan en el cliente por defecto. + +## Solución de Problemas + +| Síntoma | Causa | Solución | +| ----------------------------------- | --------------------------------------------------------------- | --------------------------------------------------------------------------- | +| Página blanca vacía | SSR renderizando un módulo dependiente de canvas | Usa `dynamic(..., { ssr: false })` o envuélvelo en un componente de cliente | +| Canvas no se muestra | El contenedor tiene altura cero | Establece `fullScreen: { zIndex: -1 }` o asígnale dimensiones explícitas | +| El cambio de opciones no se refleja | No se creó una nueva referencia del objeto | Usa `useMemo` con el arreglo de dependencias adecuado | +| El preset no funciona | El preset no se cargó antes de la inicialización del contenedor | Llama a `loadXPreset(engine)` dentro del callback `init` | + +## Próximos Pasos + +- Explora las [Demostraciones Interactivas](/demos/) para configuraciones listas para usar. +- Lee la [Referencia de Opciones](/options/) para cada parámetro disponible. +- Consulta la página de [Presets](/demos/presets) para más presets preconstruidos como nieve, estrellas y luciérnagas. diff --git a/websites/website/docs/es/guides/nuxt.md b/websites/website/docs/es/guides/nuxt.md new file mode 100644 index 00000000000..c06c1b75597 --- /dev/null +++ b/websites/website/docs/es/guides/nuxt.md @@ -0,0 +1,463 @@ +--- +title: Integración con Nuxt +description: Guía paso a paso para integrar tsParticles en una aplicación Nuxt 3 / Nuxt 4. +--- + +# Integración con Nuxt + +Esta guía cubre la integración de tsParticles en un proyecto **Nuxt 3** (y Nuxt 4) usando el wrapper oficial `@tsparticles/vue3`. Nuxt se ejecuta tanto del lado del servidor como del cliente, por lo que debes proteger los componentes de partículas contra SSR. + +## Instalación + +Instala el wrapper de Vue 3 y el paquete del motor de tu elección: + +```bash +npm install @tsparticles/vue3 tsparticles +``` + +Para un paquete más pequeño, instala `@tsparticles/slim` en lugar de `tsparticles`: + +```bash +npm install @tsparticles/vue3 @tsparticles/slim +``` + +## Uso Básico + +Nuxt renderiza componentes en el servidor por defecto. Dado que tsParticles necesita la API `canvas` del navegador, debes envolver el componente `` en una etiqueta ``: + +```vue + + + + + +``` + +El envoltorio `` asegura que el componente `` solo se monte en el navegador, evitando discrepancias de hidratación. + +## Configuración + +Usa el tipo `ISourceOptions` completo para una configuración segura en cuanto a tipos. Puedes definir tus opciones en línea o importarlas desde un archivo de configuración separado: + +```vue + +``` + +## Efecto Nieve + +Crea un efecto de nevada invernal usando el preset de nieve: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +Debido a que el preset se carga con `await` de nivel superior en el ` +``` + +Los modos de interacción disponibles incluyen: `grab`, `bubble`, `connect`, `repulse`, `push`, `remove`, `attract` y `slow`. + +## Manejo de Eventos + +El componente `` emite varios eventos del ciclo de vida: + +```vue + + + +``` + +| Evento | Carga | Descripción | +| -------------------- | ----------- | ---------------------------------------------------------------------- | +| `@particles-init` | `Engine` | Se dispara una vez cuando el motor tsParticles se inicializa | +| `@particles-loaded` | `Container` | Se dispara cada vez que el contenedor termina de cargarse o recargarse | +| `@particles-destroy` | ninguno | Se dispara cuando el contenedor se destruye | + +## Ejemplo TypeScript Completo + +Un componente tipado completo con importaciones explícitas y conocimiento del ciclo de vida: + +```vue + + + + + +``` + +## Integración en Páginas + +Añade un fondo de partículas a una página específica de Nuxt colocando el componente en la plantilla de la página: + +```vue + + + + + +``` + +Si quieres partículas en **todas** las páginas, añade el componente a `layouts/default.vue` en lugar de a páginas individuales. + +## Notas sobre Nuxt 4 + +Nuxt 4 mantiene compatibilidad hacia atrás con los patrones `` y ` +``` + +## Solución de Problemas + +| Síntoma | Causa | Solución | +| ----------------------------------------- | ------------------------------------------------------ | ----------------------------------------------------------------------- | +| Pantalla en blanco / error de hidratación | `` renderizado en el servidor | Envuélvelo en `` | +| El preset no tiene efecto | El preset no se cargó antes del montaje del componente | Llama a `loadXPreset()` con await de nivel superior en ` + +``` + +El motor se inicializa una vez y se comparte entre todas las instancias de `` en tu aplicación. + +--- + +## Uso Básico + +Después de inicializar el motor, usa el componente `` en tu plantilla. Pasa la configuración como un objeto de opciones en formato JSON o una referencia a una propiedad de tu componente. + +```html + + + + + +``` + +--- + +## Renderizado Condicional + +Usa la directiva `if={}` de Riot con una propiedad de estado para retrasar el renderizado del componente de partículas hasta que el motor haya terminado de inicializarse. Esto evita cambios de layout y asegura que el componente reciba un motor listo. + +```html + + + + + +``` + +Llamar a `this.update()` activa un rerenderizado para que la etiqueta `` aparezca una vez que la promesa se resuelve. + +--- + +## Uso de Presets + +El paquete `@tsparticles/configs` proporciona configuraciones preconstruidas para efectos comunes como confeti, fuegos artificiales, nieve y estrellas. Úsalos directamente como tu objeto de opciones. + +```html + + + + + +``` + +Los presets disponibles incluyen `basic`, `confetti`, `fireworks`, `snow`, `stars` y más. Cada preset requiere que su paquete de preset correspondiente se cargue en el callback del motor. Por ejemplo, `configs.fireworks` requiere `loadFireworksPreset`. + +--- + +## Configuración Personalizada + +Construye una configuración personalizada con interactividad, múltiples formas y opciones de animación avanzadas. + +```html + + + + + +``` + +--- + +## Componente Completo + +A continuación se muestra un archivo `.riot` completo que une todo: inicialización del motor en `onBeforeMount`, renderizado condicional con estado, una configuración enriquecida con interactividad y un callback `particlesLoaded` a través del soporte integrado del componente para eventos de carga. + +```html + +
+

tsParticles + Riot.js

+ + {#if state.particlesInitialized} + + {:else} +

Cargando motor de partículas...

+ {/if} +
+ + + + +
+``` + +--- + +Ahora tienes todo lo necesario para integrar tsParticles en una aplicación Riot.js. Cada ejemplo es autónomo y está listo para copiar en tu proyecto. diff --git a/websites/website/docs/es/guides/solid.md b/websites/website/docs/es/guides/solid.md new file mode 100644 index 00000000000..3fe77273f5a --- /dev/null +++ b/websites/website/docs/es/guides/solid.md @@ -0,0 +1,512 @@ +--- +title: Integración con SolidJS +description: Guía paso a paso para integrar tsParticles en una aplicación SolidJS usando el wrapper oficial @tsparticles/solid. +--- + +# Integración con SolidJS + +Esta guía cubre la integración de tsParticles en un proyecto **SolidJS** usando el wrapper oficial `@tsparticles/solid`. El modelo de reactividad de grano fino de SolidJS funciona bien con tsParticles — los cambios en las opciones activan actualizaciones específicas del canvas sin reinicialización completa. + +## Instalación + +Instala el wrapper de SolidJS y el paquete del motor de tu elección: + +```bash +npm install @tsparticles/solid tsparticles +``` + +Para un paquete más pequeño, usa `@tsparticles/slim` en su lugar: + +```bash +npm install @tsparticles/solid @tsparticles/slim +``` + +## Uso Básico + +SolidJS se ejecuta completamente en el navegador (sin SSR), por lo que no necesitas protegerte contra el renderizado del servidor. Sin embargo, el motor debe inicializarse de forma asíncrona antes de renderizar partículas. + +Usa `initParticlesEngine` dentro de `onMount` para cargar las funcionalidades del motor, luego renderiza condicionalmente el componente `` con ``: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [initialized, setInitialized] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setInitialized(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +El componente `` asegura que el elemento `` solo se inserte en el DOM después de que el motor esté listo. + +## Inicialización del Motor + +La función `initParticlesEngine` acepta un callback que recibe la instancia de `Engine`. Usa este callback para registrar las funcionalidades que tu configuración necesita: + +```tsx +import { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import { loadSlim } from "@tsparticles/slim"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Engine } from "@tsparticles/engine"; + +// Mínimo — solo formas básicas y movimiento +initParticlesEngine((engine: Engine) => loadSlim(engine)).then(() => { + console.log("Motor listo (slim)"); +}); + +// Completo — todas las funcionalidades incluidas +initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => { + console.log("Motor listo (completo)"); +}); + +// Solo preset — solo las funcionalidades necesarias para un preset específico +initParticlesEngine((engine: Engine) => loadConfettiPreset(engine)).then(() => { + console.log("Preset de confeti cargado"); +}); +``` + +Llama a `initParticlesEngine` una vez en tu aplicación — normalmente en el `onMount` del componente raíz. La instancia del motor se almacena en caché, por lo que las llamadas posteriores vuelven inmediatamente. + +## Renderizado Condicional + +Usa el flujo de control `` de SolidJS para diferir el renderizado hasta que el motor esté inicializado: + +```tsx +import { createSignal, Show, onMount } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import type { Engine } from "@tsparticles/engine"; +import type { Component } from "solid-js"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + Cargando partículas...

}> + +
+ ); +}; +``` + +La propiedad `fallback` muestra un indicador de carga mientras el motor se inicializa. + +## Uso de Presets + +Usa `@tsparticles/configs` para configuraciones rápidas y prediseñadas: + +```bash +npm install @tsparticles/configs +``` + +```tsx +import configs from "@tsparticles/configs"; +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + +
+ + +
+
+ ); +}; + +export default App; +``` + +Las configuraciones disponibles incluyen: `basic`, `bubbles`, `snow`, `stars`, `fireworks`, `confetti`, `links` y más. + +## Partículas Interactivas + +Añade interacciones de clic y hover configurando la sección `interactivity`: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 60 }, + links: { enable: true, distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 4 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +- **Modos de hover**: `grab`, `bubble`, `repulse`, `attract`, `slow`, `connect` +- **Modos de clic**: `push`, `remove`, `repulse`, `bubble`, `attract`, `pause` + +## Configuración Personalizada + +Una configuración personalizada completa con múltiples formas de partículas, paletas de colores y ajustes de movimiento: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0a0a23" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { enable: true, rotateX: 600, rotateY: 1200 }, + }, + number: { + value: 40, + density: { enable: true }, + }, + opacity: { + value: { min: 0.3, max: 0.8 }, + animation: { + enable: true, + speed: 0.5, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + animation: { + enable: true, + speed: 2, + sync: false, + }, + }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.3, + width: 1, + }, + shape: { + type: ["circle", "square", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + twinkle: { + particles: { + enable: true, + frequency: 0.05, + opacity: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "bubble" }, + }, + modes: { + repulse: { distance: 120 }, + bubble: { distance: 200, size: 10, opacity: 0.8 }, + }, + }, + detectRetina: true, + }; + + return ( + + + + ); +}; + +export default App; +``` + +## Ejemplo TypeScript Completo + +Un componente tipado completo con referencia al contenedor, inicialización del motor y controles manuales: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [container, setContainer] = createSignal(undefined); + const [paused, setPaused] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#1a1a2e" }, + particles: { + color: { value: "#e94560" }, + number: { value: 80 }, + links: { enable: true, color: "#e94560", distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 5 } }, + }, + }; + + const particlesLoaded = (c: Container) => { + setContainer(c); + }; + + const togglePause = () => { + const c = container(); + if (c) { + if (paused()) { + c.play(); + } else { + c.pause(); + } + setPaused(!paused()); + } + }; + + return ( + + + + + ); +}; + +export default App; +``` + +## Opciones Dinámicas con Señales + +Una de las fortalezas de SolidJS es la reactividad de grano fino — puedes usar señales para manejar las opciones de partículas y el canvas se actualizará de manera eficiente: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [color, setColor] = createSignal("#ff0000"); + const [particleCount, setParticleCount] = createSignal(60); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + // las opciones son un objeto normal — se leerán reactivamente a través + // del seguimiento interno del componente Particles + const options = (): ISourceOptions => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#000" }, + particles: { + color: { value: color() }, + number: { value: particleCount() }, + links: { enable: true, color: color() }, + move: { enable: true }, + }, + }); + + return ( + + {}} /> +
+ + +
+
+ ); +}; + +export default App; +``` + +Debido a que `options` es una función que accede a señales, cada vez que `color()` o `particleCount()` cambian, el componente `` recibe un nuevo objeto de opciones y aplica solo las propiedades cambiadas al canvas existente. + +## Preset con Personalizaciones + +Carga un preset, luego combina personalizaciones para un efecto a medida: + +```tsx +import { loadSnowPreset } from "@tsparticles/preset-snow"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadSnowPreset(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + preset: "snow", + fullScreen: { zIndex: -1 }, + background: { color: "#0d0d2b" }, + particles: { + // Sobrescribe el color de la nieve a azul + color: { value: "#88ccff" }, + // Aumenta el número de copos + number: { value: 300 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +El preset proporciona valores por defecto para cada opción, y tus personalizaciones se fusionan encima — solo necesitas especificar las propiedades que quieres cambiar. + +## Solución de Problemas + +| Síntoma | Causa | Solución | +| ----------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------- | +| Elemento DOM en blanco | Motor no inicializado antes del renderizado | Envuelve `` en `` | +| No se ven partículas | Falta `move.enable` o `number.value` | Asegúrate de `particles.move.enable: true` y `particles.number.value > 0` | +| Canvas detrás del contenido | Falta `zIndex` en fullScreen | Usa `fullScreen: { zIndex: -1 }` | +| El cambio de opciones no se refleja | La referencia del objeto no cambia | Envuelve las opciones en una función o store; evita objetos estáticos | +| Motor no encontrado | Falta la importación de `loadFull` o `loadSlim` | Instala `tsparticles` o `@tsparticles/slim` y llama a `loadFull(engine)` | + +## Próximos Pasos + +- Explora el [Playground de Configuraciones](/playground/configs) para configuraciones listas para usar. +- Lee la [Referencia de Opciones](/options/) para la lista completa de parámetros. +- Navega por el [código fuente de SolidJS](https://github.com/tsparticles/solid) en GitHub para conocer los detalles internos del wrapper. diff --git a/websites/website/docs/es/guides/stencil.md b/websites/website/docs/es/guides/stencil.md new file mode 100644 index 00000000000..8b41109872f --- /dev/null +++ b/websites/website/docs/es/guides/stencil.md @@ -0,0 +1,359 @@ +--- +title: Guía de Stencil +description: Guía completa para integrar tsParticles con componentes Stencil. +--- + +# Guía de Stencil + +## Tabla de Contenidos + +1. [Instalación](#instalación) +2. [Registro de Elementos Personalizados](#registro-de-elementos-personalizados) +3. [Uso Básico](#uso-básico) +4. [Inicialización del Motor](#inicialización-del-motor) +5. [Configuración Personalizada](#configuración-personalizada) +6. [Ciclo de Vida del Componente](#ciclo-de-vida-del-componente) +7. [Ejemplo TypeScript](#ejemplo-typescript) + +--- + +## Instalación + +Instala el wrapper de Stencil y el motor tsParticles a través de npm: + +```bash +npm install @tsparticles/stencil tsparticles +``` + +Opcionalmente instala un paquete de preset para reducir la configuración manual: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Registro de Elementos Personalizados + +El paquete `@tsparticles/stencil` proporciona una función `defineCustomElements` que registra el elemento personalizado `` en el navegador. Llámala una vez antes de usar el componente en cualquier parte de tu aplicación. + +```tsx +import { defineCustomElements } from "@tsparticles/stencil/loader"; + +// Registra el elemento +defineCustomElements(); +``` + +Para proyectos Stencil que usan carga perezosa, llama esto dentro de `componentWillLoad` o en el componente raíz de tu aplicación para asegurar que el elemento esté disponible antes del renderizado. + +--- + +## Uso Básico + +Una vez que el elemento personalizado está registrado, puedes usar `` en tu JSX con una propiedad `options` y un callback `init` para cargar las funcionalidades del motor necesarias. + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +@Component({ tag: "my-particles" }) +export class MyParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## Inicialización del Motor + +La propiedad `init` recibe la instancia del motor y te permite cargar las funcionalidades que necesitas. Este es el lugar recomendado para llamar a `loadSlim`, `loadFull` o plugins individuales de actualizadores/interacciones. + +```tsx +import { loadSlim } from "@tsparticles/slim"; +import { loadFull } from "tsparticles"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// Opción A: ligero (círculos, movimiento básico, enlaces) +init={async engine => { await loadSlim(engine); }} + +// Opción B: conjunto completo de funcionalidades (todas las formas, efectos, presets) +init={async engine => { await loadFull(engine); }} + +// Opción C: presets (confeti, fuegos artificiales, nieve, estrellas) +init={async engine => { await loadConfettiPreset(engine); }} +``` + +La instancia del motor también es accesible después de la inicialización a través del atributo `container-id`, permitiéndote controlar programáticamente el sistema de partículas más tarde si es necesario. + +--- + +## Configuración Personalizada + +A continuación se muestra una configuración completa con interactividad, múltiples tipos de formas y modos de hover/clic. + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const fullOptions: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { + color: "#0f0f23", + }, +}; + +@Component({ tag: "app-particles" }) +export class AppParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## Ciclo de Vida del Componente + +En Stencil, el hook de ciclo de vida recomendado para la configuración única es `componentWillLoad`. Úsalo para registrar elementos personalizados y gestionar el estado de inicialización para que el componente `` solo se renderice cuando el motor esté preparado. + +```tsx +import { Component, h, State } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ tag: "app-root" }) +export class AppRoot { + @State() private engineReady = false; + + private options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { + enable: true, + speed: 1, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#1a1a2e" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.engineReady = true; + } + + render() { + return ( +
+

tsParticles + Stencil

+ {this.engineReady && ( + { + await loadSlim(engine); + }} + /> + )} +
+ ); + } +} +``` + +Usar `@State()` asegura que el componente se vuelva a renderizar cuando el motor esté listo, y el renderizado condicional evita que el contenedor de partículas se monte antes de que el elemento personalizado esté definido. + +--- + +## Ejemplo TypeScript + +Aquí hay un componente de aplicación Stencil completo y tipado que integra tsParticles con el preset slim, interactividad hover y un tema oscuro personalizado. + +```tsx +import { Component, h, State, Prop } from "@stencil/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ + tag: "app-home", + styleUrl: "app-home.css", + shadow: true, +}) +export class AppHome { + @State() private initialized = false; + + @Prop() readonly title: string = "Bienvenido"; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.initialized = true; + } + + private handleInit = async (engine: Engine): Promise => { + await loadSlim(engine); + }; + + private handleLoaded = async (container?: Container): Promise => { + this.container = container; + console.log("Contenedor de partículas cargado:", container?.id); + }; + + render() { + return ( +
+

{this.title}

+

Desarrollado por tsParticles y Stencil

+ + {this.initialized && ( + + )} +
+ ); + } +} +``` + +El evento `particlesLoaded` se dispara una vez que se renderiza el primer frame, dándote acceso a la instancia de `Container` para control programático (reproducir, pausar, detener, cambiar temas). + +--- + +Ahora tienes todo lo necesario para integrar tsParticles en una aplicación Stencil. Cada ejemplo es autónomo y está listo para copiar en tu proyecto. diff --git a/websites/website/docs/es/guides/svelte.md b/websites/website/docs/es/guides/svelte.md new file mode 100644 index 00000000000..90e42657ef7 --- /dev/null +++ b/websites/website/docs/es/guides/svelte.md @@ -0,0 +1,580 @@ +--- +title: Integración con Svelte +description: Guía paso a paso para integrar tsParticles en aplicaciones Svelte y SvelteKit usando @tsparticles/svelte. +--- + +# Integración con Svelte + +El paquete `@tsparticles/svelte` proporciona un componente Svelte nativo para tsParticles. Esta guía cubre Svelte (con Vite) y SvelteKit, incluyendo opciones reactivas, manejo de eventos y múltiples instancias. + +--- + +## Instalación + +```bash +npm install @tsparticles/svelte @tsparticles/engine +``` + +Para el paquete completo o presets: + +```bash +npm install tsparticles +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +``` + +--- + +## Uso Básico + +```svelte + + + +``` + +--- + +## Inicialización del Motor + +Pasa un manejador de evento `on:init` para cargar los plugins y presets que tu aplicación necesita: + +```svelte + + + +``` + +Alternativamente, usa la utilidad `initParticlesEngine` antes del montaje: + +```svelte + + +{#if ready} + +{/if} +``` + +--- + +## Efecto Nieve + +```bash +npm install @tsparticles/preset-snow +``` + +```svelte + + + +``` + +Personaliza el comportamiento del preset fusionando opciones adicionales: + +```svelte + +``` + +--- + +## Efecto Estrellas + +```bash +npm install @tsparticles/preset-stars +``` + +```svelte + + + +``` + +--- + +## Partículas Interactivas + +Añade interactividad de hover y clic del ratón: + +```svelte + + + +``` + +--- + +## Manejo de Eventos + +```svelte + + +
+ + + +
+ + +``` + +| Evento | Detalle | Se dispara | +| -------------------- | ----------- | ----------------------------------------------------- | +| `on:init` | `Engine` | Después de que el motor se inicializa | +| `on:particlesLoaded` | `Container` | Después de que el contenedor está completamente listo | + +--- + +## Ejemplo TypeScript + +Componente tipado completo: + +```svelte + + + +``` + +--- + +## Opciones Dinámicas + +Las opciones reactivas actualizan las partículas sin recrear la instancia: + +```svelte + + +
+ +
+ + +``` + +La declaración reactiva `$:` recalcula `options` cada vez que `color` cambia, y el componente `Particles` recoge la nueva configuración automáticamente. + +--- + +## Múltiples Instancias + +Renderiza varios sistemas de partículas independientes en la misma página: + +```svelte + + +
+
+ +
+
+ +
+
+``` + +Cada componente `` obtiene su propio `id`, canvas y contexto de motor. + +--- + +## Uso con SvelteKit + +En SvelteKit, el canvas requiere el entorno del navegador. Deshabilita SSR para el componente: + +```svelte + + +{#if Component} + +{/if} +``` + +O envuelve la importación en un componente solo de cliente. Para SvelteKit 2+, también puedes usar las exclusiones SSR de `vite-plugin-svelte`. + +--- + +## Referencia de API + +| Prop | Tipo | Por Defecto | Descripción | +| --------- | ---------------- | --------------- | ------------------------------------- | +| `id` | `string` | `"tsparticles"` | ID del elemento canvas | +| `options` | `ISourceOptions` | `{}` | Objeto de configuración de partículas | +| `url` | `string` | — | URL a una configuración JSON remota | + +| Evento | Detalle | Descripción | +| -------------------- | ----------- | -------------------------------------------------------------------- | +| `on:init` | `Engine` | Se dispara cuando el motor se inicializa (úsalo para cargar plugins) | +| `on:particlesLoaded` | `Container` | Se dispara cuando el contenedor está completamente listo | + +--- + +## Solución de Problemas + +- **Canvas no visible** — Asegúrate de que el contenedor padre tenga dimensiones explícitas (`height: 100%`, `height: 100vh`, o un valor fijo en píxeles). +- **`loadFull is not a function`** — Verifica que `tsparticles` esté instalado y que estés importando `loadFull` desde `tsparticles` (no desde `@tsparticles/engine`). +- **Reactividad no funciona** — Asegúrate de que `options` sea una variable reactiva (`$:` o `let` vinculada a una fuente reactiva). Los valores `const` simples no se actualizarán. +- **SvelteKit pantalla en blanco** — Importa `@tsparticles/svelte` dinámicamente o usa la protección `browser` como se muestra en la sección de SvelteKit anterior. +- **Errores TypeScript para `event.detail`** — Usa los tipos `CustomEvent` y `CustomEvent` para los manejadores de eventos. diff --git a/websites/website/docs/es/guides/vanilla.md b/websites/website/docs/es/guides/vanilla.md new file mode 100644 index 00000000000..6f13701cfe8 --- /dev/null +++ b/websites/website/docs/es/guides/vanilla.md @@ -0,0 +1,889 @@ +--- +title: Guía de JavaScript Vanilla +description: Guía completa para integrar tsParticles con JavaScript puro. +--- + +# Guía de JavaScript Vanilla + +## Tabla de Contenidos + +1. [Comenzando](#getting-started) +2. [Partículas Básicas](#basic-particles) +3. [Efecto de Confeti](#confetti-effect) +4. [Efecto de Fuegos Artificiales](#fireworks-effect) +5. [Efecto de Cintas](#ribbons-effect) +6. [Efecto de Nieve](#snow-effect) +7. [Efecto de Red / Conexiones](#network-links-effect) +8. [Efecto de Estrellas](#stars-effect) +9. [Configuración Personalizada](#custom-configuration) +10. [Múltiples Contenedores](#multiple-containers) +11. [Controles Dinámicos](#dynamic-controls) + +--- + +## Comenzando + +### CDN (inicio rápido) + +Agrega un `
` como marcador de posición y etiquetas de script en tu HTML. Necesitas al menos el motor + un bundle, y debes llamar al cargador antes de `tsParticles.load()`. + +```html + + + + + + tsParticles – Getting Started + + + +
+ + + + + + +``` + +### npm + +```bash +npm install @tsparticles/engine @tsparticles/slim +``` + +Luego impórtalo y úsalo: + +```javascript +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +(async () => { + await loadSlim(tsParticles); + + await tsParticles.load({ + id: "tsparticles", + options: { + /* ... */ + }, + }); +})(); +``` + +> **Nota:** `@tsparticles/engine` por sí solo no dibuja nada. Debes instalar un bundle (`@tsparticles/slim` recomendado) o plugins individuales para obtener formas visibles. + +--- + +## Partículas Básicas + +Una configuración mínima que renderiza 100 partículas con forma circular, colores aleatorios y movimiento suave. En v4, los colores de las partículas se configuran mediante `paint` en lugar de la antigua propiedad `color`. + +```html + + + + + + Basic Particles + + + +
+ + + + + + +``` + +--- + +## Efecto de Confeti + +Usa el bundle dedicado `@tsparticles/confetti` para una explosión festiva con una sola llamada a una función. + +```html + + + + + + Confetti + + + + + + + + + +``` + +--- + +## Efecto de Fuegos Artificiales + +Un espectáculo de fuegos artificiales usando el bundle dedicado `@tsparticles/fireworks` con efectos de sonido. + +```html + + + + + + Fireworks + + + + + + + +``` + +--- + +## Efecto de Cintas + +Usa el bundle dedicado `@tsparticles/ribbons` para animaciones de cintas fluidas que reaccionan a la posición del ratón. + +```html + + + + + + Ribbons + + + + + + + +``` + +--- + +## Efecto de Nieve + +Suaves copos de nieve cayendo usando el catálogo de presets `@tsparticles/configs`. + +```html + + + + + + Snow Effect + + + +
+ + + + + + + +``` + +Alternativamente, usando el paquete de preset independiente: + +```html + + + + +``` + +--- + +## Efecto de Red / Conexiones + +Un visual clásico de nodos conectados con interactividad del ratón. El bundle `@tsparticles/slim` incluye la interacción de conexiones y el modo de agarre con el ratón. + +```html + + + + + + Network / Links + + + +
+ + + + + + +``` + +--- + +## Efecto de Estrellas + +Un cielo nocturno estrellado usando el catálogo de presets `@tsparticles/configs`. + +```html + + + + + + Stars Effect + + + +
+ + + + + + + +``` + +Alternativamente, usando el paquete de preset independiente: + +```html + + + + +``` + +--- + +## Configuración Personalizada + +Construye una configuración desde cero con un fondo degradado, efectos interactivos al pasar el ratón y múltiples tipos de formas usando el bundle slim. + +```html + + + + + + Custom Config + + + +

Configuración Personalizada

+
+ + + + + + +``` + +--- + +## Múltiples Contenedores + +Ejecuta múltiples instancias de partículas independientes en la misma página, cada una con su propia configuración. + +```html + + + + + + Multiple Containers + + + +
+
+
+
+ + + + + + +``` + +--- + +## Controles Dinámicos + +Inicia, detén, pausa y cambia temas programáticamente en tiempo de ejecución. + +```html + + + + + + Dynamic Controls + + + +
+
+ + + + + + +
+ + + + + + +``` + +--- + +Ahora has cubierto todos los patrones principales de integración de JavaScript Vanilla para tsParticles v4. Cada ejemplo es un archivo HTML independiente que puedes abrir en tu navegador para ver tsParticles en acción. diff --git a/websites/website/docs/es/guides/vue3.md b/websites/website/docs/es/guides/vue3.md new file mode 100644 index 00000000000..15c44511e7d --- /dev/null +++ b/websites/website/docs/es/guides/vue3.md @@ -0,0 +1,622 @@ +--- +title: Integración con Vue 3 +description: Guía paso a paso para integrar tsParticles en aplicaciones Vue 3 usando @tsparticles/vue3. +--- + +# Integración con Vue 3 + +El paquete `@tsparticles/vue3` proporciona un componente nativo de Vue 3 y un sistema de plugins para tsParticles. Esta guía cubre todo, desde la configuración básica hasta patrones avanzados como el cambio dinámico de temas y presets personalizados. + +--- + +## Instalación + +```bash +npm install @tsparticles/vue3 @tsparticles/engine +``` + +Opcionalmente instala un preset o el paquete completo: + +```bash +# Paquete completo (todas las funcionalidades) +npm install tsparticles + +# Presets específicos +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars + +# Configuraciones de utilidad +npm install @tsparticles/configs +``` + +--- + +## Uso Básico + +Registra el plugin en el punto de entrada de tu aplicación, luego usa el componente `` en cualquier parte. + +### Entrada de la App (`main.ts`) + +```typescript +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +const app = createApp(App); + +app.use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, +}); + +app.mount("#app"); +``` + +### Componente (`App.vue`) + +```vue + + + +``` + +--- + +## Usando `particlesInit` con el Componente + +Si prefieres no usar el plugin global, pasa un callback `init` directamente: + +```vue + + + +``` + +--- + +## Eventos + +El componente emite varios eventos del ciclo de vida: + +```vue + + + +``` + +--- + +## Efecto Confeti + +Usa el preset de confeti para celebraciones: + +```bash +npm install @tsparticles/preset-confetti +``` + +```vue + + + +``` + +Para una explosión única, carga el preset y luego llama a `tsParticles.load()` programáticamente dentro de un método. + +--- + +## Efecto Fuegos Artificiales + +El preset de fuegos artificiales crea explosiones de partículas de alto impacto: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```vue + + + +``` + +> **Consejo:** El preset de fuegos artificiales consume muchos recursos. Actívalo en una interacción del usuario (ej., clic de botón) alternando un `v-if` vinculado al componente. + +--- + +## Efecto Nieve + +Simula nieve cayendo con el preset de nieve: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +--- + +## Partículas Interactivas + +Añade modos de interactividad de hover y clic: + +```vue + + + +``` + +Modos de interacción disponibles: `grab`, `repulse`, `bubble`, `connect`, `push`, `remove`, `trail`, `attract`, `light`. + +--- + +## Cambio de Tema + +Intercambia dinámicamente los temas de partículas en tiempo de ejecución actualizando el objeto de opciones reactivo: + +```vue + + + +``` + +Alternativamente, usa la opción incorporada [themes](https://particles.js.org/docs/interfaces/Options_Interfaces_IOptions.IOptions.html#themes) y la propiedad `theme` en el contenedor para un cambio sin configuración. + +--- + +## Preset Personalizado desde @tsparticles/configs + +El paquete `@tsparticles/configs` exporta objetos de configuración predefinidos: + +```bash +npm install @tsparticles/configs +``` + +```vue + + + +``` + +Explora las configuraciones disponibles en el paquete `@tsparticles/configs` para diseños listos para usar. + +--- + +## Enfoques de Inicialización del Motor + +Hay dos formas de inicializar el motor: + +### 1. Plugin Global (recomendado) + +```typescript +// main.ts +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +createApp(App) + .use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, + }) + .mount("#app"); +``` + +El motor está entonces disponible globalmente y todas las instancias de `` lo comparten. + +### 2. Init a Nivel de Componente + +Pasa un callback `:init` a cada instancia de ``. Útil cuando diferentes componentes necesitan diferentes conjuntos de plugins: + +```vue + +``` + +### 3. Particles Provider (Composition API) + +Usa el provider para acceder al motor programáticamente: + +```vue + +``` + +--- + +## Exportaciones Nombradas + TypeScript + +Ejemplo TypeScript completo con todas las piezas juntas: + +```vue + + + +``` + +--- + +## Referencia de API + +| Prop | Tipo | Por Defecto | Descripción | +| --------- | ----------------------------------- | --------------- | ------------------------------------ | +| `id` | `string` | `"tsparticles"` | ID del elemento canvas | +| `options` | `ISourceOptions` | `{}` | Configuración de partículas | +| `init` | `(engine: Engine) => Promise` | — | Callback de inicialización del motor | +| `url` | `string` | — | URL para cargar configuración JSON | + +| Evento | Carga | Descripción | +| ------------------- | ----------- | --------------------------------------------------------------- | +| `@particles-loaded` | `Container` | Se dispara cuando el contenedor está completamente inicializado | +| `@particles-init` | `Engine` | Se dispara después de que el motor se inicializa | + +--- + +## Solución de Problemas + +- **Error: `tsparticles is not defined`** — Asegúrate de que `tsparticles` (o los presets que necesites) se carguen dentro del callback `init` antes de que el componente se renderice. +- **Canvas no visible** — Verifica que el contenedor padre tenga una altura no nula. Añade una regla CSS como `#tsparticles { height: 100vh; }`. +- **Problemas de rendimiento** — Reduce `fpsLimit`, disminuye `particles.number.value`, o desactiva `detectRetina` en dispositivos de gama baja. +- **SSR (Nuxt)** — El componente `` es solo de cliente. Envuélvelo en `` o usa la directiva `client:only`. diff --git a/websites/website/docs/es/guides/webcomponents.md b/websites/website/docs/es/guides/webcomponents.md new file mode 100644 index 00000000000..303f88c3d65 --- /dev/null +++ b/websites/website/docs/es/guides/webcomponents.md @@ -0,0 +1,359 @@ +# Web Components + +Usa tsParticles con Web Components nativos a través del paquete `@tsparticles/webcomponents`. Este enfoque no requiere framework — solo JavaScript vanilla y elementos personalizados. + +## Instalación + +### Vía CDN + +Incluye el núcleo de tsParticles y el paquete de Web Components: + +```html + + +``` + +### Vía npm + Build + +```bash +npm install @tsparticles/webcomponents tsparticles +``` + +Luego importa en tu paquete JavaScript: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; +``` + +## Inicialización del Motor + +Antes de que el elemento `` pueda renderizar, el motor debe inicializarse con las funcionalidades que necesitas. Llama a `initParticlesEngine` con un callback que cargue los plugins deseados: + +```javascript +import { initParticlesEngine } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +> **¿Por qué `loadFull`?** Registra todas las formas incorporadas (círculo, cuadrado, polígono, imagen, etc.), interacciones (hover, clic) y actualizadores (opacidad, tamaño, color, etc.). Para un paquete más pequeño, usa `tsparticles-slim` o elige plugins individuales. + +## Definiendo el Elemento Personalizado + +Después de la inicialización del motor, registra el elemento personalizado ``: + +```javascript +import { defineParticlesElement } from "@tsparticles/webcomponents"; + +defineParticlesElement(); +``` + +Esto registra la etiqueta `web-particles` en el `CustomElementRegistry` del navegador. Es seguro llamarlo múltiples veces — los registros duplicados se ignoran. + +## Uso Básico + +Una vez que tanto `initParticlesEngine` como `defineParticlesElement` se han ejecutado, usa el elemento directamente en HTML: + +```html + + + + + + tsParticles Web Components + + + + + + + +``` + +## Configuración Personalizada + +El elemento `` acepta configuración a través de la propiedad `options` (objeto JavaScript) o mediante JSON en el atributo `options`. + +### Vía Propiedad JavaScript + +```javascript +const el = document.querySelector("web-particles"); +el.options = { + background: { color: "#000000" }, + fpsLimit: 60, + particles: { + color: { value: ["#ff0000", "#00ff00", "#0000ff"] }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { value: 60 }, + opacity: { value: 0.6 }, + shape: { type: ["circle", "square"] }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + repulse: { distance: 200 }, + push: { quantity: 4 }, + }, + }, +}; +``` + +### Vía Atributo HTML (JSON) + +```html + +``` + +> Cuando usas el atributo `options`, el valor debe ser JSON válido. La asignación de propiedades es preferible para configuraciones complejas. + +## Creación Dinámica + +Puedes crear elementos `` completamente en JavaScript y añadirlos al DOM en cualquier momento: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +defineParticlesElement(); + +function createParticles(container, config) { + const el = document.createElement("web-particles"); + el.id = "dynamic-particles"; + el.style.position = "absolute"; + el.style.width = "100%"; + el.style.height = "100%"; + el.style.top = "0"; + el.style.left = "0"; + el.options = config; + container.appendChild(el); + return el; +} + +// Uso +const particles = createParticles(document.body, { + background: { color: "#1a1a2e" }, + particles: { + number: { value: 100 }, + links: { enable: true, color: "#e94560" }, + move: { enable: true, speed: 1 }, + }, +}); +``` + +## Extendiendo el Elemento Personalizado + +Puedes crear una subclase de `ParticlesElement` para crear tu propio elemento personalizado con configuración incorporada: + +```javascript +import { initParticlesEngine, ParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +class MyParticlesBackground extends ParticlesElement { + constructor() { + super(); + this.style.position = "fixed"; + this.style.top = "0"; + this.style.left = "0"; + this.style.width = "100%"; + this.style.height = "100%"; + this.style.zIndex = "-1"; + } + + connectedCallback() { + this.options = { + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true, speed: 2 }, + }, + }; + super.connectedCallback(); + } +} + +customElements.define("my-particles-bg", MyParticlesBackground); +``` + +Uso: + +```html + +``` + +## Acceso y Control del Contenedor + +El elemento personalizado expone la instancia de `Container` de tsParticles para control imperativo: + +```javascript +const el = document.querySelector("web-particles"); + +// Accede al contenedor (disponible después de connectedCallback) +const container = el.container; +container?.pause(); +container?.play(); + +// Destruir y limpiar +el.dispose(); +``` + +## Ejemplo Completo + +Una página HTML completa usando el módulo de Web Components con scripts CDN: + +```html + + + + + + Demo de tsParticles Web Components + + + +
+

tsParticles + Web Components

+

Elementos personalizados nativos, sin framework necesario.

+
+ + + + + + +``` + +## Referencia de API + +| Export / Propiedad | Tipo | Descripción | +| ------------------------------- | ------------------------ | ------------------------------------------------------------ | +| `initParticlesEngine(callback)` | `function` | Inicializa el motor tsParticles con cargadores de plugins | +| `defineParticlesElement()` | `function` | Registra el elemento personalizado `` | +| `ParticlesElement` | `class` | Clase base que puedes extender para elementos personalizados | +| `element.options` | `ISourceOptions` | Obtiene/establece el objeto de configuración de partículas | +| `element.container` | `Container \| undefined` | Referencia de solo lectura al `Container` subyacente | +| `element.dispose()` | `function` | Destruye la instancia de partículas y libera recursos | diff --git a/websites/website/docs/es/guides/wordpress.md b/websites/website/docs/es/guides/wordpress.md new file mode 100644 index 00000000000..86b9cae0804 --- /dev/null +++ b/websites/website/docs/es/guides/wordpress.md @@ -0,0 +1,314 @@ +--- +title: Guía de WordPress +description: Guía completa para integrar tsParticles con WordPress usando el plugin, bloques, shortcodes e integración con temas. +--- + +# Guía de WordPress + +## Tabla de Contenidos + +1. [Instalación](#instalación) +2. [Activación del Plugin](#activación-del-plugin) +3. [Uso de Widgets y Bloques](#uso-de-widgets-y-bloques) +4. [Uso de Shortcodes](#uso-de-shortcodes) +5. [Configuración con Filtros PHP](#configuración-con-filtros-php) +6. [Configuración Personalizada mediante Filtro](#configuración-personalizada-mediante-filtro) +7. [Integración con Temas](#integración-con-temas) + +--- + +## Instalación + +El plugin de tsParticles para WordPress está disponible a través del Directorio de Plugins de WordPress. Instálalo directamente desde el panel de administración de WordPress. + +### Desde el Administrador de WordPress + +1. Navega a **Plugins → Añadir nuevo** +2. Busca "tsParticles" +3. Haz clic en **Instalar ahora** en el plugin tsParticles +4. Haz clic en **Activar** + +### Instalación Manual + +1. Descarga el ZIP del plugin desde el Directorio de Plugins de WordPress o la [página de lanzamientos](https://github.com/tsparticles/wordpress/releases) +2. Navega a **Plugins → Añadir nuevo → Subir plugin** +3. Elige el archivo ZIP y haz clic en **Instalar ahora** +4. Haz clic en **Activar** + +--- + +## Activación del Plugin + +Una vez activado, el plugin registra: + +- Un **bloque de Gutenberg** llamado "tsParticles" disponible en el insertador de bloques +- Un **shortcode** `[tsparticles]` para usar en el Editor Clásico o plantillas PHP personalizadas +- Un **filtro PHP** `tsparticles_options` para que los desarrolladores inyecten configuración programáticamente +- Assets de front-end (JavaScript y CSS) que se encolan solo cuando el bloque o shortcode está presente en la página + +Después de la activación, puedes verificar que el plugin funciona visitando **Ajustes → tsParticles** en la barra lateral de administración de WordPress, donde una página de ajustes básicos puede estar disponible dependiendo de la versión del plugin. + +--- + +## Uso de Widgets y Bloques + +El plugin tsParticles añade un bloque Gutenberg personalizado para el editor de bloques (WordPress 5.0+). + +### Añadiendo el Bloque + +1. Edita cualquier entrada o página con el editor de bloques (Gutenberg) +2. Haz clic en el botón **+** (Añadir bloque) +3. Busca "tsParticles" o "Particles" +4. Haz clic en el bloque **tsParticles** para insertarlo + +### Ajustes del Bloque + +Una vez insertado, el panel de inspección del bloque (en el lado derecho) proporciona ajustes: + +- **ID del Contenedor** — un ID HTML único para el contenedor de partículas (por defecto: `tsparticles`) +- **Ancho / Alto** — establece dimensiones explícitas o usa el modo de pantalla completa +- **Z-Index** — controla la superposición relativa a otro contenido +- **Configuración** — pega un objeto JSON de opciones para personalizar completamente la apariencia de las partículas + +Para áreas de barra lateral del tema o widgets que no soportan bloques, usa el enfoque de [Shortcode](#uso-de-shortcodes) en su lugar. + +--- + +## Uso de Shortcodes + +Usa el shortcode `[tsparticles]` en el Editor Clásico, bloques HTML personalizados, o directamente en archivos de plantilla PHP para incrustar fondos de partículas en cualquier lugar de tu sitio. + +### Shortcode Básico + +``` +[tsparticles] +``` + +Esto renderiza la configuración de partículas por defecto (círculos flotantes simples sobre un fondo oscuro). + +### Shortcode con Opciones + +Pasa configuración JSON directamente en el shortcode usando el atributo `options`: + +``` +[tsparticles options='{"particles":{"number":{"value":50},"color":{"value":"#ff0000"},"shape":{"type":"circle"},"opacity":{"value":0.5},"size":{"value":{"min":1,"max":3}},"move":{"enable":true,"speed":1,"outModes":{"default":"bounce"}}},"background":{"color":"#1a1a2e"}}'] +``` + +### Shortcode en Plantillas PHP + +```php +// En el header.php o footer.php de tu tema +echo do_shortcode('[tsparticles]'); +``` + +O con opciones personalizadas: + +```php +$options = [ + 'particles' => [ + 'number' => ['value' => 80], + 'color' => ['value' => '#00d4ff'], + 'shape' => ['type' => 'circle'], + 'links' => [ + 'enable' => true, + 'distance' => 150, + 'color' => '#00d4ff', + 'opacity' => 0.3, + ], + 'move' => [ + 'enable' => true, + 'speed' => 1.5, + 'outModes' => ['default' => 'bounce'], + ], + ], + 'background' => ['color' => '#0d1117'], +]; + +echo do_shortcode('[tsparticles options=\'' . wp_json_encode($options) . '\']'); +``` + +--- + +## Configuración con Filtros PHP + +El plugin expone un filtro `tsparticles_options` que te permite sobrescribir o extender la configuración de partículas desde el archivo `functions.php` de tu tema o un plugin personalizado. Este es el enfoque recomendado para desarrolladores porque mantiene la configuración en PHP y evita JSON en línea. + +### Filtro Básico + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + $options['background'] = ['color' => '#0d1117']; + $options['particles']['number']['value'] = 100; + $options['particles']['color']['value'] = '#00d4ff'; + $options['particles']['shape']['type'] = 'circle'; + $options['particles']['opacity']['value'] = 0.6; + $options['particles']['size']['value'] = ['min' => 2, 'max' => 5]; + $options['particles']['links']['enable'] = true; + $options['particles']['links']['distance'] = 150; + $options['particles']['links']['color'] = '#00d4ff'; + $options['particles']['links']['opacity'] = 0.3; + $options['particles']['move']['enable'] = true; + $options['particles']['move']['speed'] = 1.5; + $options['particles']['move']['outModes']['default'] = 'bounce'; + return $options; +}); +``` + +Este filtro se ejecuta antes de que el shortcode o bloque se renderice, por lo que cualquier instancia de tsParticles en la página recibe la configuración personalizada. + +--- + +## Configuración Personalizada mediante Filtro + +Aquí hay una configuración personalizada completa que demuestra todo el poder del filtro — incluyendo interactividad, múltiples tipos de formas y soporte de temas. + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + + // Fondo de pantalla completa + $options['fullScreen'] = [ + 'enable' => true, + 'zIndex' => -1, + ]; + + $options['fpsLimit'] = 60; + + // Ajustes de partículas + $options['particles'] = [ + 'number' => [ + 'value' => 60, + 'density' => ['enable' => true, 'width' => 800, 'height' => 800], + ], + 'color' => [ + 'value' => ['#ff6b6b', '#feca57', '#48dbfb', '#ff9ff3', '#54a0ff'], + ], + 'shape' => [ + 'type' => ['circle', 'triangle', 'polygon'], + 'options' => [ + 'polygon' => ['sides' => 6], + ], + ], + 'opacity' => [ + 'value' => ['min' => 0.4, 'max' => 0.8], + ], + 'size' => [ + 'value' => ['min' => 3, 'max' => 8], + ], + 'links' => [ + 'enable' => true, + 'distance' => 200, + 'color' => '#ffffff', + 'opacity' => 0.15, + 'width' => 1, + ], + 'move' => [ + 'enable' => true, + 'speed' => 2, + 'direction' => 'none', + 'random' => true, + 'straight' => false, + 'outModes' => ['default' => 'out'], + ], + ]; + + // Interactividad + $options['interactivity'] = [ + 'events' => [ + 'onHover' => ['enable' => true, 'mode' => 'attract'], + 'onClick' => ['enable' => true, 'mode' => 'repulse'], + ], + 'modes' => [ + 'attract' => ['distance' => 200, 'duration' => 0.4, 'factor' => 1], + 'repulse' => ['distance' => 200, 'duration' => 0.4], + ], + ]; + + // Fondo + $options['background'] = [ + 'color' => '#0f0f23', + ]; + + // Soporte de temas — modo claro + $options['themes'] = [ + [ + 'name' => 'light', + 'default' => ['value' => false], + 'options' => [ + 'background' => ['color' => '#f0f0f5'], + 'particles' => [ + 'color' => ['value' => ['#e74c3c', '#2ecc71', '#3498db', '#f1c40f']], + 'links' => ['color' => '#333333', 'opacity' => 0.2], + ], + ], + ], + ]; + + return $options; +}); +``` + +--- + +## Integración con Temas + +Para hacer de tsParticles un fondo persistente en todo tu tema de WordPress, añade el shortcode o una llamada PHP directa al `header.php` o `footer.php` de tu tema. + +### Fondo en el Header + +```php + + +
+ +
+ +``` + +### Estilos de Fondo a Pantalla Completa + +Añade el siguiente CSS al `style.css` de tu tema o mediante `wp_add_inline_style`: + +```css +#tsparticles-background { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + z-index: -1; + pointer-events: none; +} + +/* Asegura que el contenido aparezca sobre las partículas */ +.site-content { + position: relative; + z-index: 1; +} +``` + +### Carga Condicional + +Para cargar tsParticles solo en páginas específicas: + +```php +// En functions.php — encola solo en la página principal +add_action('wp', function () { + if (is_front_page()) { + add_filter('tsparticles_options', function (array $options): array { + $options['particles']['number']['value'] = 120; + $options['particles']['color']['value'] = '#ffffff'; + $options['particles']['move']['speed'] = 0.8; + $options['background']['color'] = '#1a1a2e'; + return $options; + }); + } +}); +``` + +Combina esto con la colocación del bloque o shortcode para un fondo de partículas eficiente y específico para cada página. + +--- + +Ahora tienes todo lo necesario para integrar tsParticles en un sitio WordPress. Ya sea que prefieras el editor de bloques, los shortcodes o el control PHP completo, cada enfoque te brinda un fondo de partículas único con un esfuerzo mínimo. diff --git a/websites/website/docs/fr/guide/bundles-all.md b/websites/website/docs/fr/guide/bundles-all.md index 3a503d74d30..b1e580a903d 100644 --- a/websites/website/docs/fr/guide/bundles-all.md +++ b/websites/website/docs/fr/guide/bundles-all.md @@ -1,21 +1,42 @@ -# Bundle: All +# Bundle : All -`@tsparticles/all` charge toutes les fonctionnalites officielles et convient au prototypage rapide. +`@tsparticles/all` charge **tout** le dépôt tsParticles : chaque forme, interaction, updater, effet, chemin, easing, plugin et exportation. C'est le plus gros bundle, conçu pour le prototypage et les démos. -## Quand choisir All +## Fonctionnalités incluses -- Vous voulez toutes les fonctionnalites immediatement. -- Vous explorez rapidement plusieurs options. -- La taille du bundle est moins importante que la vitesse de setup. +Hérite de tout `tsparticles` (full) plus : + +**Toutes les formes :** arrow, cards, cog, heart, infinity, matrix, path, ribbon, rounded-polygon, rounded-rect, spiral, squircle + +**Toutes les interactions :** cannon, light, particle, pop, particles-repulse + +**Tous les effets :** bubble, filter, particles, shadow, trail + +**Tous les générateurs de path :** branches, brownian, curl-noise, curves, fractal-noise, grid, levy, perlin-noise, polygon, random, simplex-noise, spiral, svg, zig-zag + +**Tous les easing :** back, bounce, circ, cubic, elastic, expo, gaussian, linear, quad, quart, quint, sigmoid, sine, smoothstep + +**Tous les plugins couleur :** HEX, HSL, RGB, HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH + +**Tous les plugins :** absorbers, background-mask, canvas-mask, emitters (avec toutes les formes), easing (tous), export-image, export-json, export-video, infection, manual-particles, motion, poisson-disc, polygon-mask, responsive, sounds, themes, trail, zoom + +**Tous les updaters :** destroy, gradient, life, opacity, orbit, out-modes, paint, roll, rotate, size, tilt, twinkle, wobble + +## Quand l'utiliser + +- Prototypage rapide pour explorer les possibilités +- Démonstrations et vitrines +- Environnements de développement où la taille n'a pas d'importance +- **Déconseillé en production** : préférez des bundles plus ciblés ## Installation +### Avec npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/all ``` -## Exemple de configuration - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadAll } from "@tsparticles/all"; @@ -25,20 +46,48 @@ await loadAll(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { number: { value: 100 }, + shape: { type: "heart" }, move: { enable: true, speed: 2 }, }, }, }); ``` -## Pieges courants +### Avec CDN (balise ` + + +``` + +## Différence entre `tsparticles` et `@tsparticles/all` + +Voir le tableau complet sur la page [bundles-full](/fr/guide/bundles-full) pour la comparaison détaillée. + +## Erreurs courantes -- L'utiliser en production quand un bundle plus cible serait preferable. -- Appeler `tsParticles.load(...)` avant `loadAll(...)`. +- L'utiliser en production — préférez `@tsparticles/slim` ou `tsparticles` pour des bundles plus petits. +- Appeler `tsParticles.load()` avant `loadAll(tsParticles)`. -## Pages associees +## Voir aussi -- Vue d'ensemble: [`/guide/bundles`](/fr/guide/bundles) -- Matrice d'installation: [`/guide/installation`](/fr/guide/installation) +- [Vue d'ensemble des bundles](/fr/guide/bundles) +- [Guide d'installation](/fr/guide/installation) diff --git a/websites/website/docs/fr/guide/bundles-basic.md b/websites/website/docs/fr/guide/bundles-basic.md index 55a3dc08b55..c50c62b4313 100644 --- a/websites/website/docs/fr/guide/bundles-basic.md +++ b/websites/website/docs/fr/guide/bundles-basic.md @@ -1,21 +1,46 @@ -# Bundle: Basic +# Bundle : Basic -`@tsparticles/basic` convient aux configurations tres legeres avec runtime minimal. +`@tsparticles/basic` est le bundle le plus léger. Il inclut seulement l'essentiel : des cercles qui se déplacent avec opacité et taille animables. -## Quand choisir Basic +## Fonctionnalités incluses -- La taille du bundle est votre priorite principale. -- Vous avez besoin uniquement des effets de base. -- Les plugins avances ne sont pas necessaires. +**Formes :** cercle + +**Updaters (animations) :** + +- paint (couleur) +- opacity (opacité) +- out-modes (comportement à la sortie de l'écran) +- size (taille) + +**Plugins :** + +- move (mouvement) +- blend (mélange de couleurs) +- Couleurs HEX, HSL, RGB + +**N'inclut pas :** + +- Interactions souris/tactile (clic, survol, etc.) +- Liens entre particules (links) +- Autres formes (carrés, étoiles, images, polygones, etc.) +- Émetteurs, absorbeurs, sons +- Rotation, vie, roulement, inclinaison, oscillation + +## Quand l'utiliser + +- La taille du bundle est la priorité absolue +- Seuls des points qui bougent sont nécessaires +- Pas besoin d'interactions ou de formes complexes ## Installation +### Avec npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/basic ``` -## Exemple de configuration - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadBasic } from "@tsparticles/basic"; @@ -25,20 +50,48 @@ await loadBasic(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#ffffff" }, particles: { number: { value: 50 }, - move: { enable: true, speed: 1.5 }, + color: { value: ["#5bc0eb", "#fde74c", "#9bc53d"] }, + size: { + value: { min: 300, max: 400 }, + animation: { enable: true, speed: 100 }, + }, + move: { enable: true, speed: 10 }, }, }, }); ``` -## Pieges courants +### Avec CDN (balise ` + + +``` + +## Erreurs courantes -- Attendre des fonctionnalites qui appartiennent a des plugins non inclus. -- Appeler `tsParticles.load(...)` avant `loadBasic(...)`. +- Attendre des fonctionnalités qui ne sont pas incluses (ex. `links`, interactions souris), qui nécessitent des bundles supérieurs. +- Appeler `tsParticles.load()` avant `loadBasic(tsParticles)` : les formes et updaters ne sont pas encore enregistrés. +- Installer seulement `@tsparticles/engine` sans bundle : l'engine seul ne dessine rien. -## Pages associees +## Voir aussi -- Vue d'ensemble: [`/guide/bundles`](/fr/guide/bundles) -- Matrice d'installation: [`/guide/installation`](/fr/guide/installation) +- [Vue d'ensemble des bundles](/fr/guide/bundles) +- [Guide d'installation](/fr/guide/installation) diff --git a/websites/website/docs/fr/guide/bundles-confetti.md b/websites/website/docs/fr/guide/bundles-confetti.md index 7accca0d0c4..7a2a3e26be1 100644 --- a/websites/website/docs/fr/guide/bundles-confetti.md +++ b/websites/website/docs/fr/guide/bundles-confetti.md @@ -1,42 +1,83 @@ -# Bundle: Confetti +# Bundle : Confetti -`@tsparticles/confetti` expose une API ciblee pour les effets confettis avec setup minimal. +`@tsparticles/confetti` expose une API simplifiée pour créer des effets de confettis avec un seul appel de fonction. Ne nécessite pas d'interagir directement avec `tsParticles`. -## Quand choisir Confetti +## Fonctionnalités incluses -- Vous voulez des effets de celebration en un appel. -- Vous ne voulez pas cabler l'engine manuellement. -- Vous preferez une API compacte pour les evenements UI. +**Formes :** cercle, cœur, cartes (symboles français : cœurs, carreaux, trèfles, piques), emoji, images, polygone, carré, étoile + +**Plugins internes :** émetteurs, motion (respecte les préférences utilisateur de réduction d'animations) + +**Updaters :** life, roll, rotate, tilt, wobble + +**API :** `confetti(options)` ou `confetti(canvasId, options)` + +## Quand l'utiliser + +- Bouton "Félicitations !" ou "Joyeux anniversaire !" +- Effet de célébration rapide +- Vous ne voulez pas configurer l'engine manuellement ## Installation +### Avec npm/pnpm/yarn + ```bash pnpm add @tsparticles/confetti ``` -## Exemple de configuration - ```ts import { confetti } from "@tsparticles/confetti"; +// Effet de base await confetti({ - count: 80, - spread: 60, + particleCount: 100, + spread: 70, + origin: { x: 0.5, y: 0.5 }, }); -await confetti("canvas-id", { - count: 50, +// Sur un canvas spécifique +await confetti("my-canvas-id", { + particleCount: 50, angle: 90, spread: 45, + colors: ["#ff0000", "#00ff00", "#0000ff"], }); ``` -## Pieges courants +### Avec CDN (balise ` + +``` + +### Paramètres principaux + +| Paramètre | Type | Défaut | Description | +| --------------- | -------- | ------------ | ----------------------------------------------------- | +| `particleCount` | number | 50 | Nombre de confettis | +| `spread` | number | 60 | Angle de diffusion (degrés) | +| `angle` | number | 90 | Direction (degrés, 90 = vers le bas) | +| `startVelocity` | number | 30 | Vitesse initiale | +| `colors` | string[] | — | Couleurs des confettis | +| `origin` | { x, y } | { 0.5, 0.5 } | Point d'origine (0-1) | +| `drift` | number | 0 | Dérive horizontale | +| `shapes` | string[] | — | Formes : "circle", "heart", "square", "star", "cards" | + +## Erreurs courantes -- Penser que `tsParticles` est exporte par `@tsparticles/confetti`. -- Reutiliser le meme id de canvas sans le vouloir. +- Penser que `tsParticles` est exporté par `@tsparticles/confetti` — ce n'est pas le cas. +- Réutiliser le même ID de canvas sans le vouloir. +- Appeler `confetti` en boucle sans gérer les performances : utilisez un intervalle raisonnable ou arrêtez l'animation quand elle n'est pas nécessaire. -## Pages associees +## Voir aussi -- Vue d'ensemble: [`/guide/bundles`](/fr/guide/bundles) -- Bundles du playground: [`/playground/bundles`](/fr/playground/bundles) +- [Vue d'ensemble des bundles](/fr/guide/bundles) +- [Bundle fireworks](/fr/guide/bundles-fireworks) diff --git a/websites/website/docs/fr/guide/bundles-fireworks.md b/websites/website/docs/fr/guide/bundles-fireworks.md index b8ccbeec5b8..d0fb1864f0a 100644 --- a/websites/website/docs/fr/guide/bundles-fireworks.md +++ b/websites/website/docs/fr/guide/bundles-fireworks.md @@ -1,44 +1,81 @@ -# Bundle: Fireworks +# Bundle : Fireworks -`@tsparticles/fireworks` expose une API ciblee pour les effets feux d'artifice avec setup minimal. +`@tsparticles/fireworks` expose une API simplifiée pour créer des effets de feux d'artifice avec un seul appel. Prend en charge les sons, les couleurs personnalisées et le contrôle de l'instance (pause/play). -## Quand choisir Fireworks +## Fonctionnalités incluses -- Vous voulez des animations fireworks en un appel. -- Vous ne voulez pas de wiring engine direct. -- Vous preferez une API compacte pour les moments de celebration. +**Formes :** ligne, cercle (de basic) + +**Plugins internes :** émetteurs, emitters-shape-square, blend (mélange), sons (sounds) + +**Updaters :** destroy, life, paint, rotate + +**API :** `fireworks(options)`, retourne une instance contrôlable + +## Quand l'utiliser + +- Effet Nouvel An ou fête +- UI de célébration +- Vous ne voulez pas configurer l'engine manuellement ## Installation +### Avec npm/pnpm/yarn + ```bash pnpm add @tsparticles/fireworks ``` -## Exemple de configuration - ```ts import { fireworks } from "@tsparticles/fireworks"; +// Effet de base const instance = await fireworks({ - colors: ["#ffffff", "#ff0000"], - sounds: false, + colors: ["#ffffff", "#ff0000", "#00ff00", "#0000ff"], + sounds: true, }); +// Contrôle de l'instance instance?.pause(); instance?.play(); -await fireworks("canvas-id", { +// Sur un canvas spécifique +await fireworks("my-canvas", { rate: 3, speed: { min: 10, max: 25 }, + sounds: false, }); ``` -## Pieges courants +### Avec CDN (balise ` + +``` + +### Paramètres principaux + +| Paramètre | Type | Défaut | Description | +| ------------ | ------------ | ------ | ------------------------- | +| `colors` | string[] | — | Couleurs d'explosion | +| `rate` | number | — | Feux par seconde | +| `speed` | { min, max } | — | Vitesse des particules | +| `sounds` | boolean | true | Active les effets sonores | +| `gravity` | number | — | Gravité (défaut : 0) | +| `opacity` | number | — | Opacité (0-1) | +| `brightness` | { min, max } | — | Luminosité de l'explosion | + +## Erreurs courantes -- Penser que `tsParticles` est exporte par `@tsparticles/fireworks`. -- Appeler `fireworks(...)` en boucle sans gerer l'instance retournee. +- Penser que `tsParticles` est exporté par `@tsparticles/fireworks` — ce n'est pas le cas. +- Appeler `fireworks()` en boucle sans gérer l'instance : l'effet est déjà continu, pas besoin d'intervalle. +- Ne pas arrêter l'instance quand l'utilisateur change de page : appelez `instance?.pause()` ou `instance?.stop()`. -## Pages associees +## Voir aussi -- Vue d'ensemble: [`/guide/bundles`](/fr/guide/bundles) -- Bundles du playground: [`/playground/bundles`](/fr/playground/bundles) +- [Vue d'ensemble des bundles](/fr/guide/bundles) +- [Bundle confetti](/fr/guide/bundles-confetti) diff --git a/websites/website/docs/fr/guide/bundles-full.md b/websites/website/docs/fr/guide/bundles-full.md index 9902d126924..4b87d3ae881 100644 --- a/websites/website/docs/fr/guide/bundles-full.md +++ b/websites/website/docs/fr/guide/bundles-full.md @@ -1,21 +1,48 @@ -# Bundle: tsparticles (Full) +# Bundle : tsparticles (Full) -`tsparticles` est le bundle full et inclut un large ensemble de fonctionnalites officielles avec un seul loader. +`tsparticles` (npm : `tsparticles`, loader : `loadFull`) est le bundle officiel complet. Il inclut toutes les fonctionnalités du bundle Slim plus les émetteurs, absorbeurs, formes de texte, animations avancées (wobble, roll, tilt, twinkle, destroy). -## Quand choisir tsparticles (Full) +## Fonctionnalités incluses -- Vous avez besoin de nombreuses fonctionnalites officielles sans selection manuelle des plugins. -- Vous voulez une base complete prete pour la production avant d'affiner. -- Vous preferez le controle engine via l'API `tsParticles`. +Hérite de tout `@tsparticles/slim` plus : + +**Formes supplémentaires :** text (texte avec polices personnalisées) + +**Interactions externes supplémentaires :** + +- drag (glisser les particules avec la souris) +- trail (traînée derrière la souris) + +**Updaters supplémentaires :** + +- destroy (destruction des particules avec animation) +- roll (roulement) +- tilt (inclinaison 3D) +- twinkle (scintillement intermittent) +- wobble (oscillation) + +**Plugins :** + +- absorbers (absorbeurs — trous noirs qui aspirent les particules) +- emitters (émetteurs — sources continues de particules) +- emitters-shape-circle, emitters-shape-square (formes pour émetteurs) + +## Quand l'utiliser + +- Besoin d'émetteurs (particules qui apparaissent en continu) +- Besoin d'absorbeurs (particules qui sont aspirées) +- Besoin de formes de texte avec polices personnalisées +- Besoin d'animations avancées (wobble, tilt, roll, twinkle) +- Bon point d'arrivée avant de passer à des plugins individuels ## Installation +### Avec npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine tsparticles ``` -## Exemple de setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadFull } from "tsparticles"; @@ -25,20 +52,65 @@ await loadFull(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { - number: { value: 100 }, - move: { enable: true, speed: 2 }, + number: { value: 50 }, + shape: { type: "text", options: { text: ["🔥", "✨", "⭐"] } }, + size: { value: 24 }, + move: { enable: true, speed: 1 }, + wobble: { enable: true, distance: 10 }, + }, + emitters: { + direction: "top", + rate: { quantity: 2, delay: 0.3 }, }, }, }); ``` +### Avec CDN (balise ` + + +``` + +## Différence entre `tsparticles` et `@tsparticles/all` + +| Aspect | `tsparticles` (full) | `@tsparticles/all` | +| ----------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------ | +| Taille | Contenue | Très grande | +| Formes | circle, square, star, polygon, line, image, emoji, text | Toutes les formes (cœur, cartes, flèches, spirales, cog, rounded-rect, etc.) | +| Interactions | Slim + drag + trail | Toutes (cannon, light, pop, particle, repulse) | +| Path | Easing quad uniquement | 14 générateurs de path | +| Effets | Aucun | 5 effets (bubble, filter, shadow, etc.) | +| Exportations | Aucune | Image, JSON, Video | +| Plugins supplémentaires | absorbers, emitters | Tous (sounds, themes, trail, zoom, polygon-mask, canvas-mask, background-mask, etc.) | +| Easing | Quad | 15 easing | + ## Erreurs courantes -- Appeler `tsParticles.load(...)` avant `loadFull(...)`. -- Penser que c'est le meme package que `@tsparticles/all` (ce sont des bundles differents). +- Confondre `tsparticles` avec `@tsparticles/all` — ce ne sont pas les mêmes packages. +- Appeler `tsParticles.load()` avant `loadFull(tsParticles)`. +- Le package npm est `tsparticles` (pas `@tsparticles/full`), le loader est `loadFull`. -## Pages associees +## Voir aussi -- Vue d'ensemble: [`/guide/bundles`](/fr/guide/bundles) -- Matrice d'installation: [`/guide/installation`](/fr/guide/installation) +- [Vue d'ensemble des bundles](/fr/guide/bundles) +- [Guide d'installation](/fr/guide/installation) diff --git a/websites/website/docs/fr/guide/bundles-particles.md b/websites/website/docs/fr/guide/bundles-particles.md index 2a0dc7fea66..fd7a19a4657 100644 --- a/websites/website/docs/fr/guide/bundles-particles.md +++ b/websites/website/docs/fr/guide/bundles-particles.md @@ -1,42 +1,98 @@ -# Bundle: Particles +# Bundle : Particles -`@tsparticles/particles` expose une API ciblee pour des fonds de particules simples. +`@tsparticles/particles` expose une API simplifiée pour créer des fonds de particules interactifs. C'est une alternative plus riche à `@tsparticles/basic` mais avec une API dédiée au lieu de configurer l'engine manuellement. -## Quand choisir Particles +## Fonctionnalités incluses -- Vous voulez une API rapide pour des fonds de particules. -- Vous ne voulez pas brancher engine/plugins manuellement. -- Vous preferez une API compacte orientee application. +**Formes :** cercle (de basic) + +**Plugins internes :** interactivity (liens, collisions) + +**Interactions :** links (liens entre particules), collisions + +**API :** `particles(options)` ou `particles(canvasId, options)` + +## Quand l'utiliser + +- Fond de particules pour un site web +- Fond avec liens entre particules (style "nœuds") +- Vous ne voulez pas configurer l'engine manuellement ## Installation +### Avec npm/pnpm/yarn + ```bash pnpm add @tsparticles/particles ``` -## Exemple de configuration - ```ts import { particles } from "@tsparticles/particles"; +// Fond avec liens await particles({ count: 120, links: true, - linksColor: "#0ff", + color: "#ffffff", + linksColor: "#00d8ff", + radius: 3, + speed: 2, + opacity: 0.8, }); -await particles("canvas-id", { +// Sur un canvas spécifique +await particles("my-canvas", { count: 80, shape: ["circle", "square"], + links: true, }); + +// Avec couleurs personnalisées +await particles({ + count: 100, + color: ["#ff6b6b", "#4ecdc4", "#45b7d1"], + links: false, +}); +``` + +### Avec CDN (balise ` + ``` -## Pieges courants +### Paramètres principaux + +| Paramètre | Type | Défaut | Description | +| ------------ | ------------------ | ---------- | ------------------------- | +| `count` | number | 50 | Nombre de particules | +| `radius` | number | 3 | Rayon des particules | +| `speed` | number | 2 | Vitesse de déplacement | +| `opacity` | number | 0.8 | Opacité (0-1) | +| `color` | string \| string[] | "#ffffff" | Couleur(s) des particules | +| `links` | boolean | false | Afficher les liens | +| `linksColor` | string | "#ffffff" | Couleur des liens | +| `linksWidth` | number | 1 | Épaisseur des liens | +| `shape` | string[] | ["circle"] | Formes des particules | + +## Erreurs courantes -- Penser que `tsParticles` est exporte par `@tsparticles/particles`. -- Reutiliser le meme id de canvas sans le vouloir. +- Penser que `tsParticles` est exporté par `@tsparticles/particles` — ce n'est pas le cas. +- Réutiliser le même ID de canvas sans le vouloir. +- Attendre des formes avancées (étoiles, polygones) — le bundle particles est basé sur basic et utilise seulement des cercles. -## Pages associees +## Voir aussi -- Vue d'ensemble: [`/guide/bundles`](/fr/guide/bundles) -- Bundles du playground: [`/playground/bundles`](/fr/playground/bundles) +- [Vue d'ensemble des bundles](/fr/guide/bundles) +- [Guide pour démarrer](/fr/guide/getting-started) diff --git a/websites/website/docs/fr/guide/bundles-slim.md b/websites/website/docs/fr/guide/bundles-slim.md index 0090635e0e3..566f9592a3c 100644 --- a/websites/website/docs/fr/guide/bundles-slim.md +++ b/websites/website/docs/fr/guide/bundles-slim.md @@ -1,21 +1,61 @@ -# Bundle: Slim +# Bundle : Slim -`@tsparticles/slim` est le choix recommande pour la plupart des projets. +`@tsparticles/slim` est le bundle recommandé pour la plupart des projets. Il inclut tout le nécessaire pour créer des animations de particules modernes avec interactions souris, formes multiples et liens. -## Quand choisir Slim +## Fonctionnalités incluses -- Vous voulez un bon equilibre entre taille et fonctionnalites. -- Vous utilisez directement l'API engine `tsParticles`. -- Vous avez besoin de formes/interactions courantes sans tout charger. +Hérite de tout `@tsparticles/basic` plus : + +**Formes :** cercle, carré, étoile, polygone, ligne, image, emoji + +**Interactions externes (souris/tactile) :** + +- attract +- bounce +- bubble +- connect +- destroy +- grab +- parallax +- pause +- push +- remove +- repulse +- slow + +**Interactions entre particules :** + +- attract +- collisions +- links (liens entre particules) + +**Updaters supplémentaires :** + +- life (vie/cycle) +- rotate (rotation) + +**Plugins :** + +- interactivity (plugin pour activer les interactions) +- easing-quad (easing quadratique pour les animations) +- Couleurs HEX, HSL, RGB + +## Quand l'utiliser + +- Point de départ recommandé pour la plupart des projets +- Besoin de formes multiples (cercles, étoiles, polygones, images) +- Besoin d'interactions souris (clic, survol, bubble, repulse) +- Besoin de liens entre particules (links) +- Bon équilibre entre taille du bundle et fonctionnalités ## Installation +### Avec npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/slim ``` -## Exemple de configuration - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; @@ -25,21 +65,47 @@ await loadSlim(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#0b1020" }, particles: { number: { value: 80 }, + links: { enable: true, distance: 150 }, move: { enable: true, speed: 2 }, - links: { enable: true }, + shape: { type: ["circle", "star", "square"] }, }, }, }); ``` -## Pieges courants +### Avec CDN (balise ` + + +``` + +## Erreurs courantes -- Appeler `tsParticles.load(...)` avant `loadSlim(...)`. -- Melanger des versions differentes entre engine et plugins. +- Appeler `tsParticles.load()` avant `loadSlim(tsParticles)`. +- Mélanger des versions différentes entre engine et bundle — maintenez-les alignés. +- Attendre des fonctionnalités qui sont seulement dans les bundles supérieurs (émetteurs, absorbeurs, texte, wobble) : `tsparticles` (full) ou des plugins individuels sont nécessaires. -## Pages associees +## Voir aussi -- Vue d'ensemble: [`/guide/bundles`](/fr/guide/bundles) -- Matrice d'installation: [`/guide/installation`](/fr/guide/installation) +- [Vue d'ensemble des bundles](/fr/guide/bundles) +- [Guide d'installation](/fr/guide/installation) diff --git a/websites/website/docs/fr/guide/bundles.md b/websites/website/docs/fr/guide/bundles.md index a8a6f46de55..6cc4c361a84 100644 --- a/websites/website/docs/fr/guide/bundles.md +++ b/websites/website/docs/fr/guide/bundles.md @@ -1,104 +1,184 @@ # Guide des bundles -Cette page vous aide a choisir le bon bundle `tsParticles` et a le configurer rapidement. - -## Comparaison des packages - -| Package | Ideal pour | Style de setup | -| ------------------------ | -------------------------------------------------------------------- | ---------------------------------------------- | -| `@tsparticles/basic` | Configurations tres legeres | `tsParticles` + `await loadBasic(tsParticles)` | -| `@tsparticles/slim` | La plupart des sites/apps | `tsParticles` + `await loadSlim(tsParticles)` | -| `tsparticles` | Ensemble complet de fonctionnalites officielles avec controle engine | `tsParticles` + `await loadFull(tsParticles)` | -| `@tsparticles/all` | Toutes les fonctionnalites, prototypage rapide | `tsParticles` + `await loadAll(tsParticles)` | -| `@tsparticles/confetti` | Effets confettis en un appel | `await confetti(options)` | -| `@tsparticles/fireworks` | Effets feux d'artifice en un appel | `await fireworks(options)` | -| `@tsparticles/particles` | API simple pour fond de particules | `await particles(options)` | -| `@tsparticles/ribbons` | Effets ribbons en un appel | `await ribbons(options)` | - -## Guides par bundle - -- Basic: [`/guide/bundles-basic`](/fr/guide/bundles-basic) -- Slim: [`/guide/bundles-slim`](/fr/guide/bundles-slim) -- tsparticles (Full): [`/guide/bundles-full`](/fr/guide/bundles-full) -- All: [`/guide/bundles-all`](/fr/guide/bundles-all) -- Confetti: [`/guide/bundles-confetti`](/fr/guide/bundles-confetti) -- Fireworks: [`/guide/bundles-fireworks`](/fr/guide/bundles-fireworks) -- Particles: [`/guide/bundles-particles`](/fr/guide/bundles-particles) -- Ribbons (demo + docs): [`/demos/recipes/ribbons`](/fr/demos/recipes/ribbons) · - -## Installation - -Installez le parcours package qui correspond a votre cas d'usage. - -```bash -pnpm add @tsparticles/engine @tsparticles/basic -pnpm add @tsparticles/engine @tsparticles/slim -pnpm add @tsparticles/engine tsparticles -pnpm add @tsparticles/engine @tsparticles/all -pnpm add @tsparticles/confetti -pnpm add @tsparticles/fireworks -pnpm add @tsparticles/particles -pnpm add @tsparticles/ribbons +tsParticles est modulaire. Le package `@tsparticles/engine` contient seulement le moteur de base ; pour avoir des effets visibles, vous devez enregistrer des **formes** (quoi dessiner), des **updaters** (comment animer), des **interactions** (comment réagir à la souris/au tactile) et des **plugins** (fonctionnalités supplémentaires). Tout cela se fait via les **bundles**. + +## Catégories de bundles + +| Catégorie | Bundle | API | +| --------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------- | +| Engine + loader | `@tsparticles/basic`, `@tsparticles/slim`, `tsparticles`, `@tsparticles/all` | `tsParticles.load({ id, options })` | +| API dédiée | `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles`, `@tsparticles/ribbons` | `confetti({...})`, `fireworks({...})`, etc. | + +## Tableau comparatif complet + +Légende : ● = inclus, ○ = non inclus + +| Fonctionnalité | basic | slim | full (`tsparticles`) | all | +| --------------------------------------------------------------------------------------------------- | ----- | ---- | -------------------- | ------------------ | +| **Formes (shapes)** | | | | | +| Cercle (circle) | ● | ● | ● | ● | +| Carré (square) | ○ | ● | ● | ● | +| Étoile (star) | ○ | ● | ● | ● | +| Polygone (polygon) | ○ | ● | ● | ● | +| Ligne (line) | ○ | ● | ● | ● | +| Image (image) | ○ | ● | ● | ● | +| Emoji | ○ | ● | ● | ● | +| Texte (text) | ○ | ○ | ● | ● | +| Cartes (cards) | ○ | ○ | ○ | ● | +| Cœur (heart) | ○ | ○ | ○ | ● | +| Flèches (arrow) | ○ | ○ | ○ | ● | +| Rounded rect | ○ | ○ | ○ | ● | +| Rounded polygon | ○ | ○ | ○ | ● | +| Spirale (spiral) | ○ | ○ | ○ | ● | +| Squircle | ○ | ○ | ○ | ● | +| Cog (engrenage) | ○ | ○ | ○ | ● | +| Infini (infinity) | ○ | ○ | ○ | ● | +| Matrice (matrix) | ○ | ○ | ○ | ● | +| Path | ○ | ○ | ○ | ● | +| Ruban (ribbon) | ○ | ○ | ○ | ● | +| **Interactions externes (souris/tactile)** | | | | | +| Attract | ○ | ● | ● | ● | +| Bounce | ○ | ● | ● | ● | +| Bubble | ○ | ● | ● | ● | +| Connect | ○ | ● | ● | ● | +| Destroy | ○ | ● | ● | ● | +| Grab | ○ | ● | ● | ● | +| Parallax | ○ | ● | ● | ● | +| Pause | ○ | ● | ● | ● | +| Push | ○ | ● | ● | ● | +| Remove | ○ | ● | ● | ● | +| Repulse | ○ | ● | ● | ● | +| Slow | ○ | ● | ● | ● | +| Drag | ○ | ○ | ● | ● | +| Trail | ○ | ○ | ● | ● | +| Cannon | ○ | ○ | ○ | ● | +| Particle | ○ | ○ | ○ | ● | +| Pop | ○ | ○ | ○ | ● | +| Light | ○ | ○ | ○ | ● | +| **Interactions entre particules** | | | | | +| Links (liens) | ○ | ● | ● | ● | +| Collisions (collisions) | ○ | ● | ● | ● | +| Attract | ○ | ● | ● | ● | +| Repulse | ○ | ○ | ○ | ● | +| **Updaters (animations)** | | | | | +| Opacité | ● | ● | ● | ● | +| Taille (size) | ● | ● | ● | ● | +| Out modes (sortie d'écran) | ● | ● | ● | ● | +| Paint (couleur) | ● | ● | ● | ● | +| Rotation (rotate) | ○ | ● | ● | ● | +| Life (vie/cycle) | ○ | ● | ● | ● | +| Destroy (destruction) | ○ | ○ | ● | ● | +| Roll (roulement) | ○ | ○ | ● | ● | +| Tilt (inclinaison) | ○ | ○ | ● | ● | +| Twinkle (scintillement) | ○ | ○ | ● | ● | +| Wobble (oscillation) | ○ | ○ | ● | ● | +| Gradient | ○ | ○ | ○ | ● | +| Orbit | ○ | ○ | ○ | ● | +| **Plugins** | | | | | +| Move (mouvement) | ● | ● | ● | ● | +| Blend (mélange) | ● | ● | ● | ● | +| Émetteurs (emitters) | ○ | ○ | ● | ● | +| Absorbeurs (absorbers) | ○ | ○ | ● | ● | +| Sons (sounds) | ○ | ○ | ○ | ● | +| Motion (préférences utilisateur) | ○ | ○ | ○ | ● | +| Thèmes (themes) | ○ | ○ | ○ | ● | +| Polygon mask | ○ | ○ | ○ | ● | +| Canvas mask | ○ | ○ | ○ | ● | +| Background mask | ○ | ○ | ○ | ● | +| Export (image, json, video) | ○ | ○ | ○ | ● | +| Manual particles | ○ | ○ | ○ | ● | +| Responsive | ○ | ○ | ○ | ● | +| Trail | ○ | ○ | ○ | ● | +| Zoom | ○ | ○ | ○ | ● | +| Poisson disc | ○ | ○ | ○ | ● | +| **Chemins (path)** | | | | | +| Tous les paths | ○ | ○ | ○ | ● (14 générateurs) | +| **Effets** | | | | | +| Bubble, Filter, Shadow, etc. | ○ | ○ | ○ | ● (5 effets) | +| **Easing** | | | | | +| Quad | ○ | ● | ● | ● | +| Back, Bounce, Circ, Cubic, Elastic, Expo, Gaussian, Linear, Quart, Quint, Sigmoid, Sine, Smoothstep | ○ | ○ | ○ | ● | +| **Plugins couleur** | | | | | +| HEX, HSL, RGB | ● | ● | ● | ● | +| HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH | ○ | ○ | ○ | ● | + +### Bundles à API dédiée + +| Fonctionnalité | confetti | fireworks | particles | ribbons | +| ---------------- | ----------------------------------------------------------- | ---------------------- | ------------------ | ----------------- | +| Formes | cercle, cœur, cartes, emoji, image, polygone, carré, étoile | ligne | (de basic) | ruban | +| Interactions | — | — | links + collisions | — | +| Plugins spéciaux | émetteurs, motion | émetteurs, sons, blend | — | émetteurs, motion | +| API d'appel | `confetti(opts)` | `fireworks(opts)` | `particles(opts)` | `ribbons(opts)` | + +## Guide de sélection + +```mermaid +flowchart TD + A[Je dois démarrer rapidement ?] -->|Oui| B[J'utilise un préréglage ?] + A -->|Non| C[Quelle taille de bundle ?] + B -->|Oui| D["@tsparticles/configs + @tsparticles/slim"] + B -->|Non| E["Confettis ? → @tsparticles/confetti"] + B -->|Non| F["Feux d'artifice ? → @tsparticles/fireworks"] + B -->|Non| G["Fond de particules ? → @tsparticles/particles"] + B -->|Non| H["Rubans ? → @tsparticles/ribbons"] + C -->|"Minimale (cercles uniquement)"| I["@tsparticles/basic"] + C -->|"Moyenne (formes + interactions)"| J["@tsparticles/slim"] + C -->|"Maximale (toutes les fonctionnalités)"| K["tsparticles (loadFull)"] + C -->|"Tout le dépôt"| L["@tsparticles/all"] ``` -Besoin de liens CDN et d'autres variantes de gestionnaires de packages ? - -- Voir [`/guide/installation`](/fr/guide/installation). - -## Exemples de setup - -### Bundles avec engine + loader (`basic`, `slim`, `full`, `all`) - -```ts -import { tsParticles } from "@tsparticles/engine"; -import { loadSlim } from "@tsparticles/slim"; - -await loadSlim(tsParticles); - -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - number: { value: 80 }, - move: { enable: true, speed: 2 }, - }, - }, -}); +**Règles pratiques :** + +1. La plupart des projets partent de `@tsparticles/slim`. +2. Si la taille du bundle est critique et que seuls des cercles qui bougent suffisent : `@tsparticles/basic`. +3. S'il faut des émetteurs, absorbeurs, texte, wobble/tilt/roll : `tsparticles` avec `loadFull`. +4. Pour le prototypage rapide avec toutes les fonctionnalités : `@tsparticles/all`. +5. Pour des effets ciblés (confettis, feux d'artifice, particules, rubans) avec configuration minimale : bundles à API dédiée. + +## Installation rapide + +| Bundle | Commande npm | Fonction loader | URL CDN | +| ------------------------ | ------------------------------------------------- | ------------------------ | -------------------------------------------------------------- | +| `@tsparticles/basic` | `pnpm add @tsparticles/engine @tsparticles/basic` | `loadBasic(tsParticles)` | `@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| `@tsparticles/slim` | `pnpm add @tsparticles/engine @tsparticles/slim` | `loadSlim(tsParticles)` | `@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| `tsparticles` (full) | `pnpm add @tsparticles/engine tsparticles` | `loadFull(tsParticles)` | `tsparticles@4/tsparticles.bundle.min.js` | +| `@tsparticles/all` | `pnpm add @tsparticles/engine @tsparticles/all` | `loadAll(tsParticles)` | `@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| `@tsparticles/confetti` | `pnpm add @tsparticles/confetti` | `confetti(opts)` | `@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| `@tsparticles/fireworks` | `pnpm add @tsparticles/fireworks` | `fireworks(opts)` | `@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| `@tsparticles/particles` | `pnpm add @tsparticles/particles` | `particles(opts)` | `@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| `@tsparticles/ribbons` | `pnpm add @tsparticles/ribbons` | `ribbons(opts)` | `@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | + +**Remarque :** avec les bundles basic/slim/full/all, vous DEVEZ appeler `load*` avant `tsParticles.load()`. Les fichiers CDN exposent la fonction loader globalement mais NE l'appellent PAS automatiquement. Les bundles confetti/fireworks/particles/ribbons ont une API autonome — appelez directement `confetti()`, `fireworks()`, etc. + +Exemple CDN pour `@tsparticles/slim` : + +```html + + + ``` -Pour les autres presets, remplacez uniquement l'import/fonction du loader : +Exemple CDN pour `@tsparticles/confetti` : -- `@tsparticles/basic` -> `loadBasic` -- `tsparticles` -> `loadFull` -- `@tsparticles/all` -> `loadAll` - -### API ciblees (`confetti`, `fireworks`, `particles`, `ribbons`) - -```ts -import { confetti } from "@tsparticles/confetti"; -import { fireworks } from "@tsparticles/fireworks"; -import { particles } from "@tsparticles/particles"; -import { ribbons } from "@tsparticles/ribbons"; - -await confetti({ count: 80, spread: 60 }); -await fireworks({ sounds: false }); -await particles({ count: 100, links: true }); -await ribbons({ count: 5, spread: 0 }); +```html + + ``` -Ces API sont ideales si vous voulez integrer rapidement sans connecter manuellement de nombreux plugins engine. - -## Regles pratiques de selection - -1. Commencez avec `@tsparticles/slim` dans la plupart des projets. -2. Utilisez `@tsparticles/basic` si la taille du bundle est votre priorite principale et que les fonctionnalites restent simples. -3. Utilisez `tsparticles` quand vous avez besoin d'une base full avec beaucoup de fonctionnalites et `loadFull`. -4. Utilisez `@tsparticles/all` pour le prototypage ou quand vous avez besoin de nombreuses fonctionnalites immediatement. -5. Utilisez `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles` ou `@tsparticles/ribbons` quand votre UI a besoin d'un effet cible avec un setup minimal. +Voir aussi le [guide d'installation](/fr/guide/installation) pour CDN, npm, yarn et les détails sur les fichiers. -## Pages associees +## Pages associées -- Bundles cibles dans le playground : [`/playground/bundles`](/fr/playground/bundles) -- Parcours de demarrage : [`/guide/getting-started`](/fr/guide/getting-started) -- Matrice d'installation : [`/guide/installation`](/fr/guide/installation) -- Vue d'ensemble des wrappers : [`/guide/wrappers`](/fr/guide/wrappers) +- [Guide pour démarrer](/fr/guide/getting-started) +- [Guide d'installation](/fr/guide/installation) +- [Catalogue de préréglages](/demos/presets) +- [Catalogue de palettes](/demos/palettes) +- [Catalogue de formes](/demos/shapes) diff --git a/websites/website/docs/fr/guide/color-formats.md b/websites/website/docs/fr/guide/color-formats.md index f2210276ed3..7df311a3014 100644 --- a/websites/website/docs/fr/guide/color-formats.md +++ b/websites/website/docs/fr/guide/color-formats.md @@ -1,6 +1,6 @@ # Formats de couleur -tsParticles accepte plusieurs formats de couleurs parmi des options telles que `background`, `particles.color` et les paramètres du plugin. +tsParticles accepte plusieurs formats de couleurs parmi des options telles que `background`, `particles.paint` et les paramètres du plugin. ## Formats courants diff --git a/websites/website/docs/fr/guide/getting-started.md b/websites/website/docs/fr/guide/getting-started.md index 85ffecb4f72..4821e3caeb3 100644 --- a/websites/website/docs/fr/guide/getting-started.md +++ b/websites/website/docs/fr/guide/getting-started.md @@ -1,106 +1,198 @@ # Mise en route -Ce chemin est la configuration fiable la plus rapide pour `tsParticles` en 2026. +tsParticles est une bibliothèque JavaScript/TypeScript pour créer des animations de particules, confettis, feux d'artifice et bien plus. Elle fonctionne dans tous les navigateurs modernes et est disponible en package npm ou via CDN avec une balise ` + + + + +
+ + + +``` + +> **Note** : même avec les bundles CDN, vous devez appeler `loadSlim(tsParticles)` (ou `loadBasic` / `loadFull` / `loadAll`) avant d'utiliser `tsParticles.load()`. Les bundles CDN exposent la fonction de loader globalement mais ne l'appellent pas automatiquement. + +Le même schéma s'applique pour `@tsparticles/basic` → `loadBasic`, `tsparticles` → `loadFull`, `@tsparticles/all` → `loadAll`. + +### Parcours C — Bundles spécialisés avec API dédiée (confettis, feux d'artifice, particules) + +Certains bundles ont leur propre API simplifiée, sans passer par `tsParticles.load()` : + +```html + + + + + + + + + +``` + +Même chose pour `fireworks()`, `particles()`, `ribbons()`. -- `@tsparticles/slim` : la plupart des applications devraient démarrer ici. -- `@tsparticles/basic` : ensemble de fonctionnalités plus petit pour les configurations très légères. -- `@tsparticles/all` : tout est inclus, le plus simple pour un prototypage rapide. +## Quel bundle choisir ? -Si vous avez besoin d'une API ciblée au lieu d'une configuration directe `tsParticles` : +| Bundle | npm | Quand l'utiliser | +| ------------------------ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | +| `@tsparticles/basic` | `loadBasic(tsParticles)` | Minimum vital : cercles, mouvement, opacité, taille. | +| `@tsparticles/slim` | `loadSlim(tsParticles)` | **Choix recommandé pour la plupart des projets.** Ajoute les interactions (clic/survol), liens entre particules, images, étoiles, polygones. | +| `tsparticles` | `loadFull(tsParticles)` | Ensemble complet de fonctionnalités officielles : émetteurs, absorbeurs, formes texte, roll, wobble, trail. | +| `@tsparticles/all` | `loadAll(tsParticles)` | **Tout** le dépôt : chaque forme, interaction, effet, easing, chemin, export. Pour prototypage uniquement. | +| `@tsparticles/confetti` | `confetti(options)` | Confettis en un appel. API dédiée. | +| `@tsparticles/fireworks` | `fireworks(options)` | Feux d'artifice en un appel. API dédiée. | +| `@tsparticles/particles` | `particles(options)` | Fond de particules simplifié. API dédiée. | +| `@tsparticles/ribbons` | `ribbons(options)` | Effet rubans. API dédiée. | -- `@tsparticles/particles` : API d'arrière-plan de particules simplifiée -- `@tsparticles/confetti` : API de confettis en un seul appel -- `@tsparticles/fireworks` : API de feux d'artifice en un seul appel +Plus de détails : [`/guide/bundles`](/fr/guide/bundles). -## 5) Utilisez les préréglages/configurations lorsque vous avez besoin de vitesse +## Utiliser des préréglages prédéfinis -Si vous préférez les effets prédéfinis : +Le package `@tsparticles/configs` contient des dizaines de configurations prêtes à l'emploi (absorbeurs, bulles, neige, étoiles, gravité, collisions, etc.). ```bash -pnpm add @tsparticles/configs +pnpm add @tsparticles/engine @tsparticles/slim @tsparticles/configs ``` -Chargez ensuite une configuration par clé, comme l'[application `demo/vite`](https://github.com/tsparticles/tsparticles/blob/main/demo/vite/src/main.ts). +```ts +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import "@tsparticles/configs"; + +await loadSlim(tsParticles); -Si vous préférez les configurations basées sur les noms de préréglages, utilisez le catalogue de préréglages officiel dans [`/demos/presets`](/fr/demos/presets). +// Charge un préréglage par nom +await tsParticles.load({ + id: "tsparticles", + options: { preset: "snow" }, +}); +``` -## Carte de documentation rapide +Avec CDN : -- Options racine : [`/options/`](/fr/options/) -- Référence des wrappers : [`/guide/wrappers`](/fr/guide/wrappers) -- Catalogue de préréglages : [`/demos/presets`](/fr/demos/presets) -- Catalogue de palettes : [`/demos/palettes`](/fr/demos/palettes) -- Catalogue de formes : [`/demos/shapes`](/fr/demos/shapes) -- Migration depuis particles.js : [`/migrations/particles-js`](/fr/migrations/particles-js) -- Formats couleur : [`/guide/color-formats`](/fr/guide/color-formats) -- Cycle de vie du conteneur : [`/guide/container-lifecycle`](/fr/guide/container-lifecycle) -- Plugins et personnalisation : [`/guide/plugins-customization`](/fr/guide/plugins-customization) +```html + + + + +``` -## Dépannage +## Références rapides -- Écran vide : vérifiez que `#tsparticles` existe avant d'appeler `tsParticles.load`. -- Fonctionnalité manquante : vous avez probablement besoin d'un autre plugin/package (forme, interaction, mise à jour). -- Tapez les erreurs sur les options : gardez vos packages alignés sur la même version majeure/mineure. +- Documentation des options : [`/options/`](/fr/options/) +- Guide des bundles : [`/guide/bundles`](/fr/guide/bundles) +- Catalogue de préréglages : [`/demos/presets`](/fr/demos/presets) +- Catalogue de palettes : [`/demos/palettes`](/fr/demos/palettes) +- Catalogue de formes : [`/demos/shapes`](/fr/demos/shapes) +- Wrappers pour frameworks : [`/guide/wrappers`](/fr/guide/wrappers) +- Formats couleur : [`/guide/color-formats`](/fr/guide/color-formats) +- Cycle de vie du conteneur : [`/guide/container-lifecycle`](/fr/guide/container-lifecycle) +- Plugins et personnalisation : [`/guide/plugins-customization`](/fr/guide/plugins-customization) + +## Résolution des problèmes + +| Problème | Cause probable | Solution | +| ------------------------------------------------------ | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| Écran blanc, aucune particule | `#tsparticles` n'existe pas dans le DOM quand vous appelez `tsParticles.load()` | Vérifiez que le DIV est présent avant le script, ou utilisez `DOMContentLoaded` | +| Écran blanc, aucune particule | Vous avez installé seulement `@tsparticles/engine` | Vous devez aussi installer un bundle (`@tsparticles/slim`) ou des plugins, car l'engine seul n'a pas de formes à dessiner | +| Erreur "loadBasic/loadSlim/loadFull is not a function" | Bundle non installé ou import erroné | `pnpm add @tsparticles/slim` et importez `{ loadSlim }` | +| Les particules ne bougent pas | `move.enable` n'est pas défini à `true` | Ajoutez `move: { enable: true, speed: 2 }` | +| Fonctionnalité manquante (ex. liens, collisions) | Le bundle choisi n'inclut pas cette fonctionnalité | Passez à un bundle plus riche (`@tsparticles/slim` ou `tsparticles`) ou installez le plugin spécifique | +| Erreurs de type TypeScript | Versions des packages non alignées | Maintenez engine et bundle sur la même version majeure/mineure | diff --git a/websites/website/docs/fr/guide/installation.md b/websites/website/docs/fr/guide/installation.md index 9ddd19711d7..1069e5a03e4 100644 --- a/websites/website/docs/fr/guide/installation.md +++ b/websites/website/docs/fr/guide/installation.md @@ -1,109 +1,147 @@ # Installation -Cette page reprend la matrice d'installation du README principal de `tsParticles`. +## Choisissez votre parcours -Reference officielle : +| Scénario | Commande | +| ----------------------------------- | ------------------------------------------------- | +| Démarrage rapide (recommandé) | `pnpm add @tsparticles/engine @tsparticles/slim` | +| Minimum indispensable | `pnpm add @tsparticles/engine @tsparticles/basic` | +| Ensemble complet de fonctionnalités | `pnpm add @tsparticles/engine tsparticles` | +| Tout l'écosystème | `pnpm add @tsparticles/engine @tsparticles/all` | +| Confettis uniquement | `pnpm add @tsparticles/confetti` | +| Feux d'artifice uniquement | `pnpm add @tsparticles/fireworks` | +| Fond de particules | `pnpm add @tsparticles/particles` | +| Effet rubans | `pnpm add @tsparticles/ribbons` | -## Choisir votre parcours +> **Important** : `@tsparticles/engine` seul ne dessine rien. Vous devez toujours ajouter un bundle (pour charger les formes et animations) ou des plugins individuels. Voir le [guide des bundles](/fr/guide/bundles). -- **Demarrage rapide** : `@tsparticles/engine` + `@tsparticles/slim` -- **Runtime personnalise plus leger** : `@tsparticles/engine` + seulement les plugins necessaires -- **API ciblees** : `@tsparticles/particles`, `@tsparticles/confetti`, `@tsparticles/fireworks`, ou `@tsparticles/ribbons` -- **Toutes les fonctionnalites incluses** : `@tsparticles/all` +## Avec npm -## Hebergement / CDN - -Utilisez l'un de ces fournisseurs (ou hebergez vos fichiers buildes vous-meme). - -### jsDelivr - -- -- -- -- -- -- -- -- - -### cdnjs +```bash +# engine + slim (recommandé pour la plupart des projets) +npm install @tsparticles/engine @tsparticles/slim -- +# engine + basic (minimum) +npm install @tsparticles/engine @tsparticles/basic -### unpkg +# engine + full (tsparticles) +npm install @tsparticles/engine tsparticles -- -- -- -- -- -- -- -- +# engine + all (tout) +npm install @tsparticles/engine @tsparticles/all -## Installation via gestionnaire de packages +# Bundle à API dédiée (pas besoin d'engine explicite) +npm install @tsparticles/confetti +npm install @tsparticles/fireworks +npm install @tsparticles/particles +npm install @tsparticles/ribbons +``` -### npm +## Avec yarn ```bash -npm install @tsparticles/engine +yarn add @tsparticles/engine @tsparticles/slim +# ... même schéma pour les autres bundles ``` -### yarn +## Avec pnpm ```bash -yarn add @tsparticles/engine +pnpm add @tsparticles/engine @tsparticles/slim +# ... même schéma pour les autres bundles ``` -### pnpm +## Avec CDN (balise ` + + + + +``` -- [`/guide/getting-started`](/fr/guide/getting-started) -- [`/guide/wrappers`](/fr/guide/wrappers) -- [`/demos/presets`](/fr/demos/presets) -- [`/migrations/particles-js`](/fr/migrations/particles-js) +Avec les bundles à API dédiée : -## Compatibilite legacy +```html + + +``` -Si vous migrez d'anciennes integrations particles.js, utilisez le package de compatibilite : +## Pages associées -- npm : -- jsDelivr : +- [Pour démarrer](/fr/guide/getting-started) +- [Guide des bundles](/fr/guide/bundles) +- [Catalogue de préréglages](/demos/presets) +- [Wrappers framework](/fr/guide/wrappers) diff --git a/websites/website/docs/fr/guides/angular.md b/websites/website/docs/fr/guides/angular.md new file mode 100644 index 00000000000..c9c13f22f79 --- /dev/null +++ b/websites/website/docs/fr/guides/angular.md @@ -0,0 +1,631 @@ +--- +title: Intégration Angular +description: Guide étape par étape pour intégrer tsParticles dans des applications Angular à l'aide de @tsparticles/angular. +--- + +# Intégration Angular + +Le package `@tsparticles/angular` fournit des composants Angular, des modules et des services pour tsParticles. Ce guide couvre l'approche traditionnelle avec `NgModule` ainsi que les composants autonomes Angular 17+. + +--- + +## Installation + +```bash +npm install @tsparticles/angular @tsparticles/engine +``` + +Pour l'ensemble complet des fonctionnalités, installez le bundle complet : + +```bash +npm install tsparticles +``` + +Packages de préréglages optionnels : + +```bash +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +``` + +--- + +## Utilisation de base (NgModule) + +### 1. Importer le module + +```typescript +import { NgModule } from "@angular/core"; +import { BrowserModule } from "@angular/platform-browser"; +import { NgParticlesModule } from "@tsparticles/angular"; +import { AppComponent } from "./app.component"; + +@NgModule({ + declarations: [AppComponent], + imports: [BrowserModule, NgParticlesModule], + bootstrap: [AppComponent], +}) +export class AppModule {} +``` + +### 2. Initialiser le moteur + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d47a1", + }, + fpsLimit: 120, + particles: { + number: { + value: 80, + }, + color: { + value: "#ffffff", + }, + shape: { + type: "circle", + }, + opacity: { + value: 0.5, + }, + size: { + value: { min: 1, max: 5 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Conteneur de particules chargé", container); + } +} +``` + +### 3. Template + +```html + +``` + +--- + +## Détails d'initialisation du moteur + +La méthode `NgParticlesService.init()` doit être appelée exactement une fois, généralement dans `AppComponent.ngOnInit()`. Elle reçoit un callback où vous chargez les plugins/préréglages dont votre application a besoin. + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesService } from "@tsparticles/angular"; +import type { Engine } from "@tsparticles/engine"; + +@Component({ ... }) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + // Chargez seulement ce dont vous avez besoin pour des bundles plus légers + await loadBasic(engine); // formes de base + déplacement + await loadEmittersPlugin(engine); // formes d'émetteurs + }); + } +} +``` + +Fonctions de chargement disponibles depuis `tsparticles` : + +| Fonction | Description | +| ------------------- | ----------------------------------------------------- | +| `loadFull(engine)` | Toutes les fonctionnalités (plus gros bundle) | +| `loadBasic(engine)` | Formes de base (cercle, carré, polygone, etc.) | +| `loadSlim(engine)` | La plupart des fonctionnalités sans les plugins rares | +| `loadAll(engine)` | Alias déprécié pour `loadFull` | + +--- + +## Effet Confetti + +```bash +npm install @tsparticles/preset-confetti +``` + +```typescript +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// Dans le callback NgParticlesService.init : +await loadConfettiPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "confetti", + background: { + color: "transparent", + }, +}; +``` + +Ou utilisez le composant pratique `` : + +```typescript +// app.module.ts +import { NgParticlesModule } from "@tsparticles/angular"; + +@NgModule({ + imports: [NgParticlesModule], +}) +export class AppModule {} +``` + +```html + +``` + +--- + +## Effet Feux d'artifice + +```bash +npm install @tsparticles/preset-fireworks +``` + +```typescript +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; + +// Dans le callback NgParticlesService.init : +await loadFireworksPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "fireworks", + background: { + color: "#000000", + }, +}; +``` + +Ou utilisez le composant `` : + +```html + +``` + +> Évitez de lancer automatiquement les feux d'artifice ; associez-les à une action utilisateur (clic, défilement) pour éviter une utilisation excessive des ressources. + +--- + +## Configuration personnalisée des particules + +Configuration personnalisée complète avec interactivité : + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-particles", + templateUrl: "./particles.component.html", +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d0d0d", + }, + fpsLimit: 60, + particles: { + number: { + value: 100, + density: { + enable: true, + }, + }, + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + shape: { + type: ["circle", "square", "triangle"], + }, + opacity: { + value: 0.8, + random: true, + anim: { + enable: true, + speed: 1, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + random: true, + anim: { + enable: true, + speed: 4, + size_min: 1, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.3, + width: 1, + triangles: { + enable: true, + color: "#ffffff", + opacity: 0.05, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { + enable: true, + rotateX: 600, + rotateY: 600, + }, + }, + life: { + duration: { + value: 5, + random: true, + }, + count: 0, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: { + enable: true, + }, + }, + modes: { + grab: { + distance: 200, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + detectRetina: true, + }; + + particlesLoaded(container: Container): void { + console.log("Conteneur chargé", container); + } +} +``` + +```html + +``` + +--- + +## Événements + +Le composant `ngx-particles` émet l'événement `particlesLoaded` : + +```typescript +import type { Container } from "@tsparticles/engine"; + +// Méthode du composant +onParticlesLoaded(container: Container): void { + // Accéder à l'API du conteneur + container.pause(); + container.play(); + container.destroy(); + container.exportImage().then((blob) => { /* ... */ }); +} +``` + +```html + +``` + +La référence du conteneur vous donne un contrôle programmatique complet : pause, reprise, destruction, exportation, et plus encore. + +--- + +## Syntaxe de template et rendu conditionnel + +Utilisez les directives structurelles Angular pour activer/désactiver le composant : + +```html + + + +``` + +```typescript +export class AppComponent { + showParticles = true; + // ... +} +``` + +Quand `*ngIf` est évalué à `false`, le composant est détruit (y compris le canvas et toutes les instances de particules). Le recréer réinitialise tout depuis zéro. + +--- + +## Composants autonomes (Angular 17+) + +Dans Angular 17+, vous pouvez importer `NgParticlesModule` directement dans un composant autonome : + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesModule, NgParticlesService } from "@tsparticles/angular"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +@Component({ + selector: "app-particles", + standalone: true, + imports: [NgParticlesModule], + template: ` + + `, +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 50 }, + color: { value: "#fff" }, + shape: { type: "circle" }, + move: { enable: true, speed: 2 }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Chargé", container); + } +} +``` + +Aucun encapsuleur `NgModule` nécessaire — importez simplement `NgParticlesModule` dans le tableau `imports` du composant. + +--- + +## Exemple de composant complet + +### app.component.ts + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + title = "tsParticles Angular Démo"; + + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadSlim(engine); + }); + } + + particlesOptions: ISourceOptions = { + autoPlay: true, + background: { + color: "#1e1e2e", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMask: { + cover: { + color: "#1e1e2e", + }, + enable: false, + }, + fullScreen: { + enable: true, + zIndex: -1, + }, + detectRetina: true, + fpsLimit: 60, + particles: { + color: { + value: "#cdd6f4", + }, + links: { + color: "#cdd6f4", + distance: 150, + enable: true, + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1, + }, + number: { + value: 60, + }, + opacity: { + value: 0.6, + }, + size: { + value: { min: 1, max: 3 }, + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Particules chargées", container); + } +} +``` + +### app.component.html + +```html +
+ + +
+

{{ title }}

+

Les particules s'exécutent en arrière-plan.

+
+
+``` + +### app.component.css + +```css +:host { + display: block; + width: 100%; + height: 100%; +} +``` + +--- + +## Référence API + +| Composant | Sélecteur | Description | +| --------------- | --------------- | --------------------------------------- | +| Particules | `ngx-particles` | Composant système de particules complet | +| Confetti | `ngx-confetti` | Effet confetti préconfiguré | +| Feux d'artifice | `ngx-fireworks` | Effet feux d'artifice préconfiguré | + +### Entrées `ngx-particles` + +| Entrée | Type | Défaut | Description | +| --------- | ---------------- | --------------- | ---------------------------------- | +| `id` | `string` | `"tsparticles"` | ID de l'élément canvas | +| `options` | `ISourceOptions` | `{}` | Configuration des particules | +| `url` | `string` | — | URL de configuration JSON distante | + +### Sorties `ngx-particles` + +| Sortie | Payload | Description | +| ----------------- | ----------- | ----------------------------------------- | +| `particlesLoaded` | `Container` | Émise lorsque le conteneur est initialisé | + +--- + +## Dépannage + +- **Canvas blanc / invisible** — Assurez-vous que l'élément parent a une hauteur définie (ex. `height: 100vh`). Le canvas prend les dimensions du conteneur. +- **`NgParticlesService.init()` appelée plusieurs fois** — Appelez-la une seule fois, généralement dans `AppComponent.ngOnInit()`. Les appels suivants sont sans danger mais redondants. +- **Module non trouvé** — Vérifiez que `@tsparticles/angular` est listé dans les dépendances de `package.json` et que vous avez importé `NgParticlesModule`. +- **`NullInjectorError: No provider for NgParticlesService`** — Vous devez importer `NgParticlesModule` (ou le ré-exporter) dans le module où vous fournissez le composant. diff --git a/websites/website/docs/fr/guides/astro.md b/websites/website/docs/fr/guides/astro.md new file mode 100644 index 00000000000..3601166740a --- /dev/null +++ b/websites/website/docs/fr/guides/astro.md @@ -0,0 +1,384 @@ +# Intégration Astro + +Utilisez tsParticles dans votre site Astro avec le package d'intégration officiel `@tsparticles/astro`. + +## Installation + +Installez l'intégration Astro et le cœur tsParticles via votre gestionnaire de paquets : + +```bash +npm install @tsparticles/astro tsparticles +``` + +```bash +pnpm add @tsparticles/astro tsparticles +``` + +```bash +yarn add @tsparticles/astro tsparticles +``` + +## Initialisation du moteur + +tsParticles utilise une architecture modulaire. Avant d'afficher les particules, vous devez initialiser le moteur avec les fonctionnalités dont vous avez besoin. Créez un script client (ex. `src/scripts/particles-init.ts`) ou utilisez une balise ` +``` + +> La prop `id` est transmise au `
` conteneur du canvas sous-jacent. Utilisez-la pour le style ou l'accès impératif via `document.getElementById()`. + +## Support TypeScript + +L'intégration est livrée avec des déclarations TypeScript complètes. Utilisez `ISourceOptions` de `@tsparticles/engine` pour typer votre configuration : + +```typescript +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { + value: 50, + density: { enable: true }, + }, + opacity: { value: 0.5 }, + shape: { type: "circle" }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + repulse: { distance: 200 }, + }, + }, +}; +``` + +## Configuration personnalisée + +Voici une configuration plus élaborée que vous pouvez intégrer dans n'importe quelle page Astro : + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + autoPlay: true, + background: { + color: "#0d47a1", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMode: { + enable: true, + zIndex: -1, + }, + fpsLimit: 120, + particles: { + color: { + value: "#ffffff", + animation: { + enable: true, + speed: 20, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + triangles: { + enable: true, + opacity: 0.1, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "out", + attract: { enable: false }, + }, + number: { + value: 80, + density: { + enable: true, + }, + }, + opacity: { + value: 0.5, + animation: { + enable: true, + speed: 1, + sync: false, + }, + }, + shape: { + type: "circle", + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 3, + sync: false, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: true, + }, + modes: { + grab: { + distance: 200, + links: { opacity: 0.5 }, + }, + push: { quantity: 4 }, + }, + }, + detectRetina: true, +}; +--- + + + + +``` + +## Utilisation des préréglages + +Au lieu de construire une configuration manuellement, chargez un préréglage pendant l'initialisation du moteur et référencez-le dans les options : + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + preset: "stars", + background: { color: "#000000" }, +}; +--- + + + + +``` + +## Intégration avec d'autres frameworks + +Comme Astro prend en charge les frameworks d'interface utilisateur comme React, Vue, Svelte et Solid, vous pouvez utiliser le composant tsParticles spécifique au framework dans des fichiers `.astro` : + +### React dans Astro + +```astro +--- +import Particles from "@tsparticles/react"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +### Vue dans Astro + +```astro +--- +import Particles from "@tsparticles/vue3"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +> La directive `client:load` indique à Astro d'hydrater le composant immédiatement au chargement de la page. Utilisez `client:visible` pour un chargement différé. + +## Exemple de page complète + +Une page Astro complète avec des particules servant d'arrière-plan animé : + +```astro +--- +import Layout from "../layouts/Layout.astro"; +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + number: { value: 100 }, + color: { value: "#ffffff" }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + size: { + value: { min: 1, max: 4 }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, +}; +--- + + +
+

Bienvenue

+

Cette page a un arrière-plan de particules propulsé par tsParticles.

+
+ +
+ + + + +``` + +## Props du composant + +| Prop | Type | Défaut | Description | +| -------------------- | ---------------- | ------------------------- | ----------------------------------------------------- | +| `id` | `string` | `"tsparticles"` | ID de l'élément DOM pour le conteneur | +| `options` | `ISourceOptions` | `{}` | Objet de configuration complet tsParticles | +| `url` | `string` | — | Charger la configuration depuis une URL JSON distante | +| `particlesClassName` | `string` | `"tsparticles-canvas-el"` | Classe CSS pour l'élément canvas | +| `container` | `object` | — | Instance `Container` préexistante (avancé) | diff --git a/websites/website/docs/fr/guides/ember.md b/websites/website/docs/fr/guides/ember.md new file mode 100644 index 00000000000..9010de1e76a --- /dev/null +++ b/websites/website/docs/fr/guides/ember.md @@ -0,0 +1,346 @@ +--- +title: Guide Ember +description: Guide complet pour intégrer tsParticles avec des applications Ember.js. +--- + +# Guide Ember + +## Table des matières + +1. [Installation](#installation) +2. [Initialisation du moteur](#initialisation-du-moteur) +3. [Utilisation de base](#utilisation-de-base) +4. [Configuration personnalisée](#configuration-personnalisée) +5. [Gestion des événements](#gestion-des-événements) +6. [Rendu conditionnel](#rendu-conditionnel) +7. [Exemple TypeScript](#exemple-typescript) + +--- + +## Installation + +Installez l'addon Ember et le moteur tsParticles via ember-cli : + +```bash +ember install @tsparticles/ember +``` + +Ceci installera l'addon et sa dépendance directe `tsparticles`. Vous pouvez optionnellement ajouter des packages de préréglages : + +```bash +npm install @tsparticles/slim +``` + +--- + +## Initialisation du moteur + +L'addon exporte un utilitaire `initParticlesEngine` que vous appelez une fois au niveau de l'application. Il reçoit un callback asynchrone où vous chargez les fonctionnalités, préréglages ou formes dont votre application a besoin. + +```typescript +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadFull } from "tsparticles"; + +// Appelez ceci lors du bootstrap de l'application +if (typeof window !== "undefined") { + void initParticlesEngine(async (engine) => { + await loadFull(engine); + }); +} +``` + +Les emplacements typiques pour cet appel sont le hook `beforeModel` de la route de l'application, le constructeur d'un contrôleur d'application, ou un initialiseur d'instance. Le singleton du moteur est initialisé une fois et partagé entre tous les composants `` de votre application. + +--- + +## Utilisation de base + +Après avoir initialisé le moteur, utilisez le composant `` dans n'importe quel template. Passez votre configuration de particules via l'argument `@options`. + +```hbs +{{! app/templates/application.hbs }} + + +``` + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, + }; +} +``` + +--- + +## Configuration personnalisée + +Construisez une configuration plus riche avec interactivité, formes multiples et densité réactive. + +```typescript +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class IndexController extends Controller { + options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, + }; +} +``` + +```hbs + +``` + +--- + +## Gestion des événements + +Le composant `` déclenche une action `@particlesLoaded` lorsque le conteneur a fini de s'initialiser et que la première image est rendue. Utilisez-la pour accéder à l'instance `Container` pour un contrôle programmatique. + +```typescript +import Controller from "@ember/controller"; +import { action } from "@ember/object"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + /* ... */ + }; + + @action + loadedCallback(container: Container) { + console.log("Particules chargées", container.id); + + // Exemple de contrôle programmatique : + setTimeout(() => { + container.pause(); + console.log("Particules mises en pause après 5 secondes"); + }, 5000); + } +} +``` + +```hbs + +``` + +Vous pouvez également utiliser le modèle de callback en ligne avec un assistant de template si vous préférez ne pas définir d'action séparée. + +--- + +## Rendu conditionnel + +Utilisez le helper `{{if}}` d'Ember avec une propriété `@tracked` pour contrôler quand le composant `` est rendu. Ceci est utile lorsque l'initialisation du moteur est asynchrone et que vous voulez éviter de rendre le composant avant que le moteur ne soit prêt. + +```typescript +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked engineReady = false; + + options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { enable: true, speed: 1, outModes: { default: "bounce" } }, + }, + background: { color: "#1a1a2e" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } +} +``` + +```hbs +{{#if this.engineReady}} + +{{else}} +

Chargement des particules...

+{{/if}} +``` + +Le décorateur `@tracked` garantit que le template se ré-affiche automatiquement une fois la promesse résolue. + +--- + +## Exemple TypeScript + +Voici un contrôleur d'application Ember complet et typé démontrant le modèle d'intégration complet avec le préréglage slim, l'interactivité et la gestion du cycle de vie. + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked private engineReady = false; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } + + @action + private handleParticlesLoaded(container: Container): void { + this.container = container; + console.log("Particules chargées dans le conteneur :", container.id); + } +} +``` + +```hbs +{{! app/templates/application.hbs }} + +{{#if this.engineReady}} +
+

tsParticles + Ember

+ +
+{{else}} +
+

Initialisation du moteur de particules...

+
+{{/if}} +``` + +--- + +Vous avez maintenant tout ce qu'il faut pour intégrer tsParticles dans une application Ember.js. Chaque exemple est autonome et prêt à être copié dans votre projet. diff --git a/websites/website/docs/fr/guides/index.md b/websites/website/docs/fr/guides/index.md new file mode 100644 index 00000000000..f5889897699 --- /dev/null +++ b/websites/website/docs/fr/guides/index.md @@ -0,0 +1,58 @@ +--- +title: Guides Pas à Pas +description: Explorez les guides spécifiques aux frameworks pour intégrer tsParticles dans votre projet. +--- + +# Guides Pas à Pas + +Bienvenue dans la section des guides tsParticles. Que vous construisiez un site statique Vanilla JS, une application monopage en React ou Vue, ou une application full-stack avec Next.js ou Nuxt, ces tutoriels pas à pas vous guideront à travers l'installation, l'utilisation de base, les configurations avancées et les effets interactifs. + +Chaque guide est autonome et inclut des exemples de code copiables pour vous permettre de démarrer rapidement. + +## Guides disponibles + +| Framework / Encapsuleur | Package | Description | +| --------------------------------- | ------------------------------------------ | ------------------------------------------------------ | +| [Vanilla JS](./vanilla) | `tsparticles` (CDN ou npm) | Intégration DOM directe avec `tsParticles.load()` | +| [React](./react) | `@tsparticles/react` | Encapsuleur React officiel avec hooks et API composant | +| [Vue 3](./vue3) | `@tsparticles/vue3` | Plugin Vue 3 officiel avec composables | +| [Angular](./angular) | `@tsparticles/angular` | Composant et module Angular officiel | +| [Svelte](./svelte) | `@tsparticles/svelte` | Composant Svelte officiel | +| [Next.js](./nextjs) | `@tsparticles/react` (avec Next.js) | Rendu côté serveur et imports dynamiques | +| [Nuxt](./nuxt) | `@tsparticles/vue3` (avec Nuxt) | Intégration SSR-safe en tant que plugin Nuxt | +| [Solid](./solid) | `@tsparticles/solid` | Encapsuleur SolidJS officiel | +| [Preact](./preact) | `@tsparticles/preact` | Composant compatible Preact | +| [Lit](./lit) | `@tsparticles/lit` | Encapsuleur web component Lit | +| [Qwik](./qwik) | `@tsparticles/qwik` | Intégration optimisée pour Qwik | +| [jQuery](./jquery) | `@tsparticles/jquery` | Plugin jQuery pour projets legacy | +| [Astro](./astro) | `@tsparticles/react` (ou tout encapsuleur) | Architecture d'îlots avec directives client | +| [Web Components](./webcomponents) | `@tsparticles/webcomponents` | Intégration API Custom Elements | +| [Stencil](./stencil) | `@tsparticles/stencil` | Encapsuleur composant Stencil | +| [Ember](./ember) | `@tsparticles/ember` | Intégration addon Ember | +| [Riot](./riot) | `@tsparticles/riot` | Encapsuleur Riot.js | +| [Inferno](./inferno) | `@tsparticles/inferno` | Composant compatible Inferno | +| [WordPress](./wordpress) | Plugin + `tsparticles` | Intégration éditeur de blocs / shortcode | + +## Choisissez votre guide + +- [Vanilla JS (JavaScript pur)](./vanilla) +- [React](./react) +- [Vue 3](./vue3) +- [Angular](./angular) +- [Svelte](./svelte) +- [Next.js](./nextjs) +- [Nuxt](./nuxt) +- [Solid](./solid) +- [Preact](./preact) +- [Lit](./lit) +- [Qwik](./qwik) +- [jQuery](./jquery) +- [Astro](./astro) +- [Web Components](./webcomponents) +- [Stencil](./stencil) +- [Ember](./ember) +- [Riot](./riot) +- [Inferno](./inferno) +- [WordPress](./wordpress) + +Bon développement ! diff --git a/websites/website/docs/fr/guides/inferno.md b/websites/website/docs/fr/guides/inferno.md new file mode 100644 index 00000000000..1075b41a084 --- /dev/null +++ b/websites/website/docs/fr/guides/inferno.md @@ -0,0 +1,373 @@ +--- +title: Guide Inferno +description: Guide complet pour intégrer tsParticles avec des applications Inferno. +--- + +# Guide Inferno + +## Table des matières + +1. [Installation](#installation) +2. [Utilisation de base](#utilisation-de-base) +3. [Initialisation du moteur](#initialisation-du-moteur) +4. [Configuration personnalisée](#configuration-personnalisée) +5. [Utilisation des préréglages](#utilisation-des-préréglages) +6. [Modèle de composant](#modèle-de-composant) +7. [Exemple TypeScript](#exemple-typescript) + +--- + +## Installation + +Installez l'encapsuleur Inferno et le moteur tsParticles via npm : + +```bash +npm install @tsparticles/inferno tsparticles +``` + +Installez optionnellement le préréglage slim pour un bundle plus léger : + +```bash +npm install @tsparticles/slim +``` + +--- + +## Utilisation de base + +Le package `@tsparticles/inferno` exporte deux éléments : `ParticlesProvider` et `Particles`. Encapsulez vos composants de particules avec `ParticlesProvider` qui accepte un callback `init` pour la configuration du moteur, puis utilisez `` pour afficher le canvas de particules. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import { loadSlim } from "@tsparticles/slim"; + +const options = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +function App() { + return ( + { + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +`ParticlesProvider` doit être un ancêtre de chaque composant ``. Il initialise le moteur une fois et le fournit via le contexte à tous les enfants. + +--- + +## Initialisation du moteur + +`ParticlesProvider` accepte une prop `init` qui reçoit l'instance du moteur. C'est ici que vous chargez les fonctionnalités, formes, préréglages ou mises à jour dont votre application a besoin. + +```tsx +// Léger — particules circulaires, mouvement de base, liaisons + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); +}}> + +// Ensemble complet — toutes les formes, interactions, effets + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); +}}> + +// Préréglage spécifique — confetti, feux d'artifice, neige, étoiles + { + const { loadConfettiPreset } = await import("@tsparticles/preset-confetti"); + await loadConfettiPreset(engine); +}}> +``` + +Utiliser `import()` dynamique dans le callback permet la séparation du code : les modules de préréglages ou de fonctionnalités ne sont chargés que lorsque le composant de particules se monte. + +--- + +## Configuration personnalisée + +Voici une configuration complète avec interactivité, types de formes multiples et un fond dégradé sombre. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, +}; + +function App() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +--- + +## Utilisation des préréglages + +Le package `@tsparticles/configs` propose des configurations préconstruites que vous pouvez passer directement à la prop `options`. Combinez-les avec le chargeur de préréglage correspondant dans le callback init de `ParticlesProvider`. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import configs from "@tsparticles/configs"; + +function App() { + return ( + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +Vous pouvez remplacer `configs.confetti` par n'importe quel préréglage disponible : `configs.basic`, `configs.fireworks`, `configs.snow`, `configs.stars`, etc. + +--- + +## Modèle de composant + +Pour les applications plus grandes, structurez votre logique de particules dans un composant dédié avec un callback `particlesLoaded` pour accéder à l'instance `Container`. + +```tsx +import { render, Component } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +class ParticlesBackground extends Component { + private container?: Container; + + handleParticlesLoaded(container?: Container) { + this.container = container; + console.log("Particules chargées :", container?.id); + } + + render() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); + } +} + +function App() { + return ( +
+

tsParticles + Inferno

+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +## Exemple TypeScript + +Voici une application Inferno complète et typée avec une configuration de particules réactive et un arrière-plan plein écran. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const particlesOptions: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +function handleInit(engine: Engine): Promise { + return import("@tsparticles/slim").then(({ loadSlim }) => loadSlim(engine)); +} + +function handleParticlesLoaded(container?: Container): void { + console.log("Conteneur tsParticles prêt :", container?.id); +} + +function App() { + return ( + +
+

tsParticles + Inferno

+

Intégration TypeScript complète

+
+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +Vous avez maintenant tout ce qu'il faut pour intégrer tsParticles dans une application Inferno. Chaque exemple est autonome et prêt à être copié dans votre projet. diff --git a/websites/website/docs/fr/guides/jquery.md b/websites/website/docs/fr/guides/jquery.md new file mode 100644 index 00000000000..420a49d1169 --- /dev/null +++ b/websites/website/docs/fr/guides/jquery.md @@ -0,0 +1,274 @@ +# Intégration jQuery + +Intégrez tsParticles dans vos projets basés sur jQuery avec l'encapsuleur officiel du plugin jQuery. + +## Installation + +### Via CDN + +Incluez jQuery, tsParticles et le plugin jQuery via des balises script : + +```html + + + +``` + +--- + +### Via npm + Build + +Installez les paquets requis : + +```bash +npm install jquery @tsparticles/jquery tsparticles +``` + +Importez dans votre projet : + +```javascript +import $ from "jquery"; +import "@tsparticles/jquery"; +``` + +## Initialisation du moteur + +Avant que les particules puissent être rendues, le moteur tsParticles doit être initialisé avec les fonctionnalités dont vous avez besoin. Cela se fait via `$.particles.init` : + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); +})(); +``` + +> **Pourquoi est-ce nécessaire ?** tsParticles utilise une architecture modulaire. `loadFull` enregistre toutes les formes, interactions et mises à jour intégrées. Vous pouvez importer des bundles plus petits (ex. `tsparticles-slim`) pour réduire la taille du bundle. + +## Utilisation de base + +Une fois le moteur initialisé et le DOM prêt, sélectionnez un élément conteneur et appelez `.particles().load()` : + +```javascript +$(document).ready(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); + + $("#tsparticles") + .particles() + .load({ + background: { + color: "#0d47a1", + }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + }, + }); +}); +``` + +L'élément conteneur doit exister dans le DOM : + +```html +
+``` + +## Configuration personnalisée + +La méthode `.load()` accepte l'objet complet `ISourceOptions`. Voici un exemple complet : + +```javascript +$("#tsparticles") + .particles() + .load({ + background: { + color: "#000000", + }, + fpsLimit: 120, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + direction: "none", + enable: true, + outModes: "bounce", + speed: 4, + }, + number: { + density: { + enable: true, + }, + value: 60, + }, + opacity: { + value: 0.6, + }, + shape: { + type: ["circle", "square", "triangle"], + }, + size: { + value: { min: 2, max: 8 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + }, + interactivity: { + events: { + onClick: { + enable: true, + mode: "push", + }, + onHover: { + enable: true, + mode: "repulse", + }, + }, + modes: { + push: { + quantity: 4, + }, + repulse: { + distance: 200, + }, + }, + }, + }); +``` + +## Chargement de préréglage + +Si vous avez installé un package de préréglage (ex. `tsparticles-preset-stars`), chargez-le lors de l'initialisation du moteur et référencez-le dans la configuration : + +```bash +npm install tsparticles-preset-stars +``` + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadStarsPreset } = await import("tsparticles-preset-stars"); + await loadStarsPreset(engine); + }); + + $("#tsparticles") + .particles() + .load({ + preset: "stars", + background: { color: "#0d47a1" }, + }); +})(); +``` + +## Gestion des événements et contrôle du conteneur + +`.particles()` retourne une instance de plugin jQuery. Pour accéder au `Container` tsParticles sous-jacent et appeler des méthodes comme `play()`, `pause()` ou `destroy()` : + +```javascript +const $container = $("#tsparticles"); + +// Charger les particules +$container.particles().load({ + /* options */ +}); + +// Lecture/pause après quelques secondes +setTimeout(() => { + const container = $container.particles().getContainer(); + container?.pause(); +}, 5000); +``` + +## Exemple complet + +Voici une page HTML complète et autonome qui charge tsParticles via CDN et affiche une scène de particules avec effets interactifs : + +```html + + + + + + tsParticles + jQuery + + + +
+ + + + + + + +``` + +## Référence API + +| Méthode | Description | +| ---------------------------------- | ------------------------------------------------------------ | +| `$.particles.init(fn)` | Initialiser le moteur avec un callback de chargeur | +| `$(el).particles()` | Créer une instance du plugin de particules sur l'élément | +| `$(el).particles().load(opts)` | Charger et démarrer la configuration des particules | +| `$(el).particles().destroy()` | Détruire l'instance de particules et nettoyer | +| `$(el).particles().getContainer()` | Retourner le `Container` sous-jacent pour contrôle impératif | diff --git a/websites/website/docs/fr/guides/lit.md b/websites/website/docs/fr/guides/lit.md new file mode 100644 index 00000000000..67a140d3efb --- /dev/null +++ b/websites/website/docs/fr/guides/lit.md @@ -0,0 +1,301 @@ +--- +title: Lit +description: Intégrez tsParticles avec Lit en utilisant l'encapsuleur officiel @tsparticles/lit pour web components. +--- + +# Intégration Lit + +Le package `@tsparticles/lit` fournit un élément personnalisé `` construit avec Lit, vous permettant d'utiliser tsParticles de manière déclarative dans tout projet Lit ou page HTML simple. + +## Installation + +```bash +npm install @tsparticles/lit tsparticles +``` + +Le package est entièrement typé et inclut les modèles de contrôleur réactif de Lit pour mettre à jour de manière réactive les options des particules. + +## Initialisation du moteur + +Appelez `initParticlesEngine` avant d'enregistrer le composant `` ou de l'importer dans votre application. Cela doit se produire exactement une fois. + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadFull } from "tsparticles"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +Pour des tailles de bundle optimisées, importez uniquement les fonctionnalités dont votre projet a besoin : + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadBasic } from "@tsparticles/basic"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +void initParticlesEngine(async (engine) => { + await loadBasic(engine); + await loadConfettiPreset(engine); +}); +``` + +## Utilisation de base + +Après l'initialisation du moteur, utilisez l'élément `` dans n'importe quel template Lit ou fichier HTML : + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private options = { + background: { + color: "#0d1117", + }, + particles: { + number: { value: 60 }, + color: { value: "#58a6ff" }, + links: { + enable: true, + color: "#58a6ff", + }, + move: { enable: true, speed: 2 }, + }, + }; + + render() { + return html` `; + } +} +``` + +La syntaxe `.options` (avec point) est la liaison de propriété Lit, garantissant que l'objet est passé par référence plutôt que sérialisé en attribut. + +## Utilisation HTML simple + +Une fois que `@tsparticles/lit` est intégré ou chargé, l'élément fonctionne aussi en HTML simple : + +```html + + + + + + + + + +``` + +Vous pouvez passer un objet d'options minimal comme attribut JSON : + +```html + +``` + +## Configuration personnalisée + +Passez une configuration tsParticles complète comme propriété Lit : + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-particles") +class MyParticles extends LitElement { + @property({ type: Object }) + options: ISourceOptions = { + background: { + color: "#0d1117", + }, + fpsLimit: 120, + fullScreen: { + enable: true, + zIndex: -1, + }, + particles: { + color: { + value: ["#ff5733", "#33ff57", "#3357ff"], + }, + links: { + color: "#ffffff", + enable: true, + opacity: 0.3, + distance: 150, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + }, + number: { + value: 100, + density: { + enable: true, + }, + }, + opacity: { + value: 0.6, + animation: { + enable: true, + speed: 0.5, + minimumValue: 0.1, + }, + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 2, + minimumValue: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + }, + modes: { + grab: { + distance: 180, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + }; + + render() { + return html` `; + } +} +``` + +## Gestion des événements + +Écoutez l'événement personnalisé `particles-loaded` émis par l'élément `` : + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import type { Container } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private handleParticlesLoaded(e: CustomEvent) { + const container = e.detail; + console.log("Particules chargées :", container); + container?.refresh(); + } + + render() { + return html` `; + } +} +``` + +## Exemple TypeScript + +Un élément Lit entièrement typé avec `initParticlesEngine`, options réactives et gestion d'événements : + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import { initParticlesEngine } from "@tsparticles/lit"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import "@tsparticles/lit"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +@customElement("particles-background") +class ParticlesBackground extends LitElement { + @property({ type: Object }) + options: ISourceOptions = {}; + + @property({ type: Boolean, attribute: "fullscreen" }) + fullscreen = true; + + protected onParticlesLoaded(e: CustomEvent) { + console.log("Conteneur prêt :", e.detail.id); + } + + render() { + return html` + + + `; + } +} +``` + +## Mises à jour dynamiques + +Comme `` utilise les propriétés réactives de Lit, changer la propriété `options` met automatiquement à jour les particules : + +```typescript +import { LitElement, html } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("dynamic-particles") +class DynamicParticles extends LitElement { + @state() + private theme: "light" | "dark" = "dark"; + + private get options(): ISourceOptions { + return this.theme === "dark" + ? { + background: { color: "#0d1117" }, + particles: { color: { value: "#58a6ff" } }, + } + : { + background: { color: "#ffffff" }, + particles: { color: { value: "#0969da" } }, + }; + } + + private toggleTheme() { + this.theme = this.theme === "dark" ? "light" : "dark"; + } + + render() { + return html` + + + `; + } +} +``` + +Le composant surveille la propriété `options` et appelle `refresh()` en interne à chaque changement, mettant à jour en continu la configuration des particules à l'exécution. diff --git a/websites/website/docs/fr/guides/nextjs.md b/websites/website/docs/fr/guides/nextjs.md new file mode 100644 index 00000000000..c406af8b971 --- /dev/null +++ b/websites/website/docs/fr/guides/nextjs.md @@ -0,0 +1,492 @@ +--- +title: Intégration Next.js +description: Guide étape par étape pour intégrer tsParticles dans une application Next.js utilisant l'App Router. +--- + +# Intégration Next.js + +Ce guide couvre l'intégration de tsParticles dans un projet Next.js en utilisant l'**App Router** (Next.js 13+). Pour le legacy Pages Router, voir la section [Legacy Pages Router](#legacy-pages-router) en bas de page. + +## Installation + +Installez l'encapsuleur `@tsparticles/react` et le moteur complet `tsparticles` (ou un bundle slim pour des builds plus légers) : + +```bash +npm install @tsparticles/react tsparticles +``` + +Si vous préférez le bundle plus petit `@tsparticles/slim` : + +```bash +npm install @tsparticles/react @tsparticles/slim +``` + +## Utilisation de base (App Router) + +Les composants de l'App Router Next.js sont côté serveur par défaut. Comme tsParticles nécessite l'API `canvas` du navigateur, vous devez marquer le composant avec la directive `"use client"`. + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesBackground() { + const particlesLoaded = useCallback((container?: Container) => { + console.log("Particules chargées", container); + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }), + [], + ); + + return ; +} +``` + +Créez ce fichier sous `components/particles-background.tsx` et importez-le dans n'importe quelle page ou layout. Comme le fichier commence par `"use client"`, il sera rendu côté client — exactement là où tsParticles doit être. + +## Changement de thème + +Combinez tsParticles avec les toggles de thème Next.js en dérivant les options de l'état actuel du thème : + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useMemo, useState, useCallback } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ThemeAwareParticles() { + const [theme, setTheme] = useState<"light" | "dark">("dark"); + + const toggleTheme = useCallback(() => { + setTheme((t) => (t === "dark" ? "light" : "dark")); + }, []); + + const particlesLoaded = useCallback((_container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { + color: theme === "dark" ? "#000000" : "#ffffff", + }, + particles: { + color: { value: theme === "dark" ? "#ffffff" : "#000000" }, + number: { value: 100 }, + links: { + enable: true, + color: theme === "dark" ? "#ffffff" : "#000000", + }, + move: { enable: true }, + }, + }), + [theme], + ); + + return ( + <> + + + + ); +} +``` + +L'objet `options` est recréé via `useMemo` à chaque changement de `theme`, donc le canvas se met à jour automatiquement. + +## Effet Confetti + +Utilisez `@tsparticles/preset-confetti` pour déclencher des confettis de célébration lors d'événements comme des clics sur un bouton : + +```bash +npm install @tsparticles/preset-confetti +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Container, ISourceOptions, Engine } from "@tsparticles/engine"; + +export default function ConfettiButton() { + const [active, setActive] = useState(false); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadConfettiPreset(engine); + }, []); + + const particlesLoaded = useCallback( + async (container?: Container) => { + if (active && container) { + await container.play(); + } + }, + [active], + ); + + const options: ISourceOptions = useMemo( + () => ({ + preset: "confetti", + fullScreen: { zIndex: 1000 }, + }), + [], + ); + + const handleCelebrate = useCallback(() => { + setActive(true); + setTimeout(() => setActive(false), 5000); + }, []); + + return ( + <> + {active && } + + + ); +} +``` + +Le callback `init` charge le préréglage confetti dans le moteur avant que les particules ne soient créées. + +## Effet Feux d'artifice + +De même, le préréglage feux d'artifice crée un spectacle pyrotechnique spectaculaire : + +```bash +npm install @tsparticles/preset-fireworks +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; +import type { Container, Engine } from "@tsparticles/engine"; + +export default function FireworksBackground() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFireworksPreset(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options = useMemo( + () => ({ + preset: "fireworks" as const, + fullScreen: { zIndex: -1 }, + background: { + color: "#000", + }, + }), + [], + ); + + return ; +} +``` + +## Exemple TypeScript complet avec référence de conteneur + +Accédez à l'instance `Container` pour contrôler l'animation par programmation (lecture, pause, destruction, exportation d'image) : + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +export default function ControllableParticles() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFull(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + fpsLimit: 120, + interactivity: { + events: { + onClick: { enable: true, mode: "push" }, + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + push: { quantity: 4 }, + repulse: { distance: 100 }, + }, + }, + particles: { + color: { value: "#ff0000" }, + links: { + enable: true, + color: "#ff0000", + distance: 150, + }, + move: { enable: true, speed: 2 }, + number: { value: 60 }, + size: { value: { min: 1, max: 5 } }, + }, + }), + [], + ); + + const handlePause = useCallback(() => { + containerRef.current?.pause(); + }, []); + + const handlePlay = useCallback(() => { + containerRef.current?.play(); + }, []); + + return ( +
+ +
+ + +
+
+ ); +} +``` + +Points clés : + +- `particlesInit` charge les fonctionnalités du moteur (ne s'exécute qu'une fois par montage du composant). +- `particlesLoaded` se déclenche à chaque fois que le conteneur est complètement initialisé. +- `containerRef` contient l'instance `Container` pour pouvoir appeler ses méthodes plus tard. + +## Performance : useMemo et useCallback + +Encapsulez toujours les options statiques ou peu changeantes dans `useMemo` et les gestionnaires d'événements dans `useCallback` pour éviter des re-rendus inutiles du canvas : + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function PerformanceExample() { + const [particlesCount, setParticlesCount] = useState(80); + + // Callback stable — jamais recréé sauf si les dépendances changent + const particlesLoaded = useCallback((container?: Container) => { + console.log("Conteneur prêt", container?.id); + }, []); + + // Objet d'options stable — empêche la réinitialisation du canvas + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: particlesCount }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [particlesCount], + ); + + return ( +
+ + +
+ ); +} +``` + +Sans ces optimisations, chaque re-rendu du parent créerait un nouvel objet `options`, provoquant la recréation du canvas. + +## Intégration dans une page + +Ajoutez un arrière-plan de particules à une mise en page sans affecter le contenu de la page : + +```tsx +// app/layout.tsx (composant serveur) +import dynamic from "next/dynamic"; + +const ParticlesBackground = dynamic(() => import("@/components/particles-background"), { ssr: false }); + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + +
{children}
+ + + ); +} +``` + +Utilisez `dynamic()` avec `ssr: false` pour garantir que le composant ne s'exécute jamais lors du rendu côté serveur. Le canvas de particules se place derrière le contenu principal via le CSS `z-index`. + +## Instances multiples + +Vous pouvez afficher plusieurs composants `Particles` indépendants sur la même page, chacun avec sa propre configuration : + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +function ParticlesGallery() { + const loaded = useCallback((c?: Container) => {}, []); + + const redOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#1a0000" }, + particles: { + color: { value: "#ff0000" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + const blueOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#00001a" }, + particles: { + color: { value: "#0000ff" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + return ( +
+ + +
+ ); +} +``` + +Chaque composant `Particles` crée un canvas indépendant avec sa propre boucle d'animation. Définissez `fullScreen: false` et donnez à chacun une hauteur fixe pour qu'ils coexistent dans le flux du document. + +## Legacy Pages Router + +Si vous utilisez le **Pages Router** de Next.js (répertoire `pages/`), l'approche est similaire mais sans la directive `"use client"`. Utilisez plutôt une importation dynamique dans le composant de page : + +```tsx +// pages/index.tsx +import dynamic from "next/dynamic"; +import type { NextPage } from "next"; + +const ParticlesComponent = dynamic(() => import("../components/particles-component"), { ssr: false }); + +const Home: NextPage = () => { + return ( +
+ +

Bienvenue

+
+ ); +}; + +export default Home; +``` + +Le composant lui-même (`components/particles-component.tsx`) est un simple composant React : + +```tsx +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesComponent() { + const particlesLoaded = useCallback((container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 80 }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [], + ); + + return ; +} +``` + +Notez que le Pages Router ne nécessite **pas** `"use client"` car les composants de page sont déjà rendus côté client par défaut. + +## Dépannage + +| Symptôme | Cause | Solution | +| ------------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------- | +| Page blanche | SSR d'un module dépendant du canvas | Utilisez `dynamic(..., { ssr: false })` ou encapsulez dans un composant client | +| Canvas non affiché | Conteneur a une hauteur nulle | Définissez `fullScreen: { zIndex: -1 }` ou donnez-lui des dimensions explicites | +| Changement d'options sans effet | Nouvelle référence d'objet non créée | Utilisez `useMemo` avec un tableau de dépendances approprié | +| Préréglage non fonctionnel | Préréglage non chargé avant init du conteneur | Appelez `loadXPreset(engine)` dans le callback `init` | + +## Prochaines étapes + +- Parcourez les [Démos interactives](/demos/) pour des configurations prêtes à l'emploi. +- Lisez la [Référence des options](/options/) pour chaque paramètre disponible. +- Consultez la page [Préréglages](/demos/presets) pour plus de préréglages préconstruits comme neige, étoiles et lucioles. diff --git a/websites/website/docs/fr/guides/nuxt.md b/websites/website/docs/fr/guides/nuxt.md new file mode 100644 index 00000000000..a79ba307783 --- /dev/null +++ b/websites/website/docs/fr/guides/nuxt.md @@ -0,0 +1,463 @@ +--- +title: Intégration Nuxt +description: Guide étape par étape pour intégrer tsParticles dans une application Nuxt 3 / Nuxt 4. +--- + +# Intégration Nuxt + +Ce guide couvre l'intégration de tsParticles dans un projet **Nuxt 3** (et Nuxt 4) en utilisant l'encapsuleur officiel `@tsparticles/vue3`. Nuxt s'exécute à la fois côté serveur et côté client, vous devez donc protéger les composants de particules contre le SSR. + +## Installation + +Installez l'encapsuleur Vue 3 et le bundle moteur de votre choix : + +```bash +npm install @tsparticles/vue3 tsparticles +``` + +Pour un bundle plus petit, installez `@tsparticles/slim` au lieu de `tsparticles` : + +```bash +npm install @tsparticles/vue3 @tsparticles/slim +``` + +## Utilisation de base + +Nuxt rend les composants sur le serveur par défaut. Comme tsParticles nécessite l'API `canvas` du navigateur, vous devez encapsuler le composant `` dans une balise `` : + +```vue + + + + + +``` + +L'encapsuleur `` garantit que le composant `` n'est monté que dans le navigateur, évitant les erreurs d'hydratation. + +## Configuration + +Utilisez le type `ISourceOptions` complet pour une configuration typée. Vous pouvez définir vos options en ligne ou les importer depuis un fichier de configuration séparé : + +```vue + +``` + +## Effet Neige + +Créez un effet de chute de neige hivernale en utilisant le préréglage neige : + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +Comme le préréglage est chargé avec `await` au niveau supérieur dans le ` +``` + +Les modes d'interaction disponibles incluent : `grab`, `bubble`, `connect`, `repulse`, `push`, `remove`, `attract` et `slow`. + +## Gestion des événements + +Le composant `` émet plusieurs événements du cycle de vie : + +```vue + + + +``` + +| Événement | Payload | Description | +| -------------------- | ----------- | ----------------------------------------------------------------------- | +| `@particles-init` | `Engine` | Se déclenche une fois lorsque le moteur tsParticles s'initialise | +| `@particles-loaded` | `Container` | Se déclenche chaque fois que le conteneur finit de charger ou recharger | +| `@particles-destroy` | aucun | Se déclenche lorsque le conteneur est détruit | + +## Exemple TypeScript complet + +Un composant typé complet avec des importations explicites et la gestion du cycle de vie : + +```vue + + + + + +``` + +## Intégration dans une page + +Ajoutez un arrière-plan de particules à une page Nuxt spécifique en plaçant le composant dans le template de la page : + +```vue + + + + + +``` + +Si vous voulez des particules sur **chaque** page, ajoutez le composant dans `layouts/default.vue` au lieu de pages individuelles. + +## Notes sur Nuxt 4 + +Nuxt 4 maintient la rétrocompatibilité avec les modèles `` et ` +``` + +## Dépannage + +| Symptôme | Cause | Solution | +| --------------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------- | +| Écran blanc / erreur d'hydratation | `` rendu sur le serveur | Encapsulez dans `` | +| Le préréglage n'a aucun effet | Préréglage non chargé avant le montage | Appelez `loadXPreset()` avec await au niveau supérieur dans ` + +``` + +Le moteur s'initialise une fois et est partagé entre toutes les instances `` de votre application. + +--- + +## Utilisation de base + +Après avoir initialisé le moteur, utilisez le composant `` dans votre template. Passez la configuration comme un objet d'options JSON-stringifié ou une référence à une propriété de votre composant. + +```html + + + + + +``` + +--- + +## Rendu conditionnel + +Utilisez la directive `if={}` de Riot avec une propriété d'état pour retarder le rendu du composant de particules jusqu'à ce que le moteur ait fini de s'initialiser. Cela évite les décalages de mise en page et garantit que le composant reçoit un moteur prêt. + +```html + + + + + +``` + +Appeler `this.update()` déclenche un re-rendu pour que la balise `` apparaisse une fois la promesse résolue. + +--- + +## Utilisation des préréglages + +Le package `@tsparticles/configs` fournit des configurations préconstruites pour des effets courants comme confetti, feux d'artifice, neige et étoiles. Utilisez-les directement comme objet d'options. + +```html + + + + + +``` + +Les préréglages disponibles incluent `basic`, `confetti`, `fireworks`, `snow`, `stars`, et plus encore. Chaque préréglage nécessite que son package de préréglage correspondant soit chargé dans le callback du moteur. Par exemple, `configs.fireworks` nécessite `loadFireworksPreset`. + +--- + +## Configuration personnalisée + +Construisez une configuration personnalisée avec interactivité, formes multiples et options d'animation avancées. + +```html + + + + + +``` + +--- + +## Composant complet + +Voici un fichier `.riot` complet qui rassemble tout : initialisation du moteur dans `onBeforeMount`, rendu conditionnel avec état, une configuration riche avec interactivité, et un callback `particlesLoaded` via le support intégré du composant pour les événements chargés. + +```html + +
+

tsParticles + Riot.js

+ + {#if state.particlesInitialized} + + {:else} +

Chargement du moteur de particules...

+ {/if} +
+ + + + +
+``` + +--- + +Vous avez maintenant tout ce qu'il faut pour intégrer tsParticles dans une application Riot.js. Chaque exemple est autonome et prêt à être copié dans votre projet. diff --git a/websites/website/docs/fr/guides/solid.md b/websites/website/docs/fr/guides/solid.md new file mode 100644 index 00000000000..cda7018bc7d --- /dev/null +++ b/websites/website/docs/fr/guides/solid.md @@ -0,0 +1,512 @@ +--- +title: Intégration SolidJS +description: Guide étape par étape pour intégrer tsParticles dans une application SolidJS en utilisant l'encapsuleur officiel @tsparticles/solid. +--- + +# Intégration SolidJS + +Ce guide couvre l'intégration de tsParticles dans un projet **SolidJS** en utilisant l'encapsuleur officiel `@tsparticles/solid`. Le modèle de réactivité fine de SolidJS fonctionne bien avec tsParticles — les changements d'options déclenchent des mises à jour ciblées du canvas sans réinitialisation complète. + +## Installation + +Installez l'encapsuleur SolidJS et le bundle moteur de votre choix : + +```bash +npm install @tsparticles/solid tsparticles +``` + +Pour un bundle plus petit, utilisez `@tsparticles/slim` : + +```bash +npm install @tsparticles/solid @tsparticles/slim +``` + +## Utilisation de base + +SolidJS s'exécute entièrement dans le navigateur (pas de SSR), vous n'avez donc pas besoin de protéger contre le rendu serveur. Cependant, le moteur doit être initialisé de manière asynchrone avant d'afficher les particules. + +Utilisez `initParticlesEngine` dans `onMount` pour charger les fonctionnalités du moteur, puis affichez conditionnellement le composant `` avec `` : + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [initialized, setInitialized] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setInitialized(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +Le composant `` garantit que l'élément `` n'est inséré dans le DOM qu'après que le moteur est prêt. + +## Initialisation du moteur + +La fonction `initParticlesEngine` accepte un callback qui reçoit l'instance `Engine`. Utilisez ce callback pour enregistrer les fonctionnalités dont votre configuration a besoin : + +```tsx +import { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import { loadSlim } from "@tsparticles/slim"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Engine } from "@tsparticles/engine"; + +// Minimal — seulement les formes de base et les déplacements +initParticlesEngine((engine: Engine) => loadSlim(engine)).then(() => { + console.log("Moteur prêt (slim)"); +}); + +// Complet — toutes les fonctionnalités incluses +initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => { + console.log("Moteur prêt (complet)"); +}); + +// Préréglage seulement — juste les fonctionnalités nécessaires pour un préréglage spécifique +initParticlesEngine((engine: Engine) => loadConfettiPreset(engine)).then(() => { + console.log("Préréglage confetti chargé"); +}); +``` + +Appelez `initParticlesEngine` une fois dans votre application — généralement dans le `onMount` du composant racine. L'instance du moteur est mise en cache, donc les appels suivants retournent immédiatement. + +## Rendu conditionnel + +Utilisez le flux de contrôle `` de SolidJS pour différer le rendu jusqu'à ce que le moteur soit initialisé : + +```tsx +import { createSignal, Show, onMount } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import type { Engine } from "@tsparticles/engine"; +import type { Component } from "solid-js"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + Chargement des particules...

}> + +
+ ); +}; +``` + +La prop `fallback` affiche un indicateur de chargement pendant l'initialisation du moteur. + +## Utilisation des préréglages + +Utilisez `@tsparticles/configs` pour des configurations rapides et préconçues : + +```bash +npm install @tsparticles/configs +``` + +```tsx +import configs from "@tsparticles/configs"; +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + +
+ + +
+
+ ); +}; + +export default App; +``` + +Les configurations disponibles incluent : `basic`, `bubbles`, `snow`, `stars`, `fireworks`, `confetti`, `links`, et plus encore. + +## Particules interactives + +Ajoutez des interactions au clic et au survol en configurant la section `interactivity` : + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 60 }, + links: { enable: true, distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 4 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +- **Modes de survol** : `grab`, `bubble`, `repulse`, `attract`, `slow`, `connect` +- **Modes de clic** : `push`, `remove`, `repulse`, `bubble`, `attract`, `pause` + +## Configuration personnalisée + +Une configuration personnalisée complète avec formes de particules multiples, palettes de couleurs et paramètres de mouvement : + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0a0a23" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { enable: true, rotateX: 600, rotateY: 1200 }, + }, + number: { + value: 40, + density: { enable: true }, + }, + opacity: { + value: { min: 0.3, max: 0.8 }, + animation: { + enable: true, + speed: 0.5, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + animation: { + enable: true, + speed: 2, + sync: false, + }, + }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.3, + width: 1, + }, + shape: { + type: ["circle", "square", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + twinkle: { + particles: { + enable: true, + frequency: 0.05, + opacity: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "bubble" }, + }, + modes: { + repulse: { distance: 120 }, + bubble: { distance: 200, size: 10, opacity: 0.8 }, + }, + }, + detectRetina: true, + }; + + return ( + + + + ); +}; + +export default App; +``` + +## Exemple TypeScript complet + +Un composant typé complet avec référence de conteneur, initialisation du moteur et contrôles manuels : + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [container, setContainer] = createSignal(undefined); + const [paused, setPaused] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#1a1a2e" }, + particles: { + color: { value: "#e94560" }, + number: { value: 80 }, + links: { enable: true, color: "#e94560", distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 5 } }, + }, + }; + + const particlesLoaded = (c: Container) => { + setContainer(c); + }; + + const togglePause = () => { + const c = container(); + if (c) { + if (paused()) { + c.play(); + } else { + c.pause(); + } + setPaused(!paused()); + } + }; + + return ( + + + + + ); +}; + +export default App; +``` + +## Options dynamiques avec signaux + +L'un des atouts de SolidJS est sa réactivité fine — vous pouvez utiliser des signaux pour piloter les options des particules et le canvas se mettra à jour efficacement : + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [color, setColor] = createSignal("#ff0000"); + const [particleCount, setParticleCount] = createSignal(60); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + // les options sont un objet normal — il sera lu de manière réactive via + // le suivi interne du composant Particle + const options = (): ISourceOptions => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#000" }, + particles: { + color: { value: color() }, + number: { value: particleCount() }, + links: { enable: true, color: color() }, + move: { enable: true }, + }, + }); + + return ( + + {}} /> +
+ + +
+
+ ); +}; + +export default App; +``` + +Comme `options` est une fonction qui accède aux signaux, chaque fois que `color()` ou `particleCount()` change, le composant `` reçoit un nouvel objet d'options et applique uniquement les propriétés modifiées au canvas existant. + +## Préréglage avec surcharges personnalisées + +Chargez un préréglage, puis fusionnez des surcharges personnalisées pour un effet adapté : + +```tsx +import { loadSnowPreset } from "@tsparticles/preset-snow"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadSnowPreset(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + preset: "snow", + fullScreen: { zIndex: -1 }, + background: { color: "#0d0d2b" }, + particles: { + // Surcharger la couleur de la neige en bleu + color: { value: "#88ccff" }, + // Augmenter le nombre de flocons + number: { value: 300 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +Le préréglage fournit des valeurs par défaut pour chaque option, et vos surcharges sont fusionnées par-dessus — vous n'avez besoin de spécifier que les propriétés que vous voulez modifier. + +## Dépannage + +| Symptôme | Cause | Solution | +| ------------------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------- | +| Élément DOM vide | Moteur non initialisé avant le rendu | Encapsulez `` dans `` | +| Aucune particule visible | `move.enable` ou `number.value` manquant | Assurez-vous `particles.move.enable: true` et `particles.number.value > 0` | +| Canvas derrière le contenu | `zIndex` manquant dans fullScreen | Utilisez `fullScreen: { zIndex: -1 }` | +| Changement d'options sans effet | La référence d'objet ne change pas | Encapsulez les options dans une fonction ou un store ; évitez les objets statiques | +| Moteur non trouvé | Import manquant de `loadFull` ou `loadSlim` | Installez `tsparticles` ou `@tsparticles/slim` et appelez `loadFull(engine)` | + +## Prochaines étapes + +- Explorez le [Terrain de jeu des configurations](/playground/configs) pour des configurations prêtes à l'emploi. +- Lisez la [Référence des options](/options/) pour la liste complète des paramètres. +- Parcourez le [code source SolidJS](https://github.com/tsparticles/solid) sur GitHub pour les détails internes de l'encapsuleur. diff --git a/websites/website/docs/fr/guides/stencil.md b/websites/website/docs/fr/guides/stencil.md new file mode 100644 index 00000000000..85c6006b994 --- /dev/null +++ b/websites/website/docs/fr/guides/stencil.md @@ -0,0 +1,359 @@ +--- +title: Guide Stencil +description: Guide complet pour intégrer tsParticles avec des composants Stencil. +--- + +# Guide Stencil + +## Table des matières + +1. [Installation](#installation) +2. [Enregistrement des éléments personnalisés](#enregistrement-des-éléments-personnalisés) +3. [Utilisation de base](#utilisation-de-base) +4. [Initialisation du moteur](#initialisation-du-moteur) +5. [Configuration personnalisée](#configuration-personnalisée) +6. [Cycle de vie du composant](#cycle-de-vie-du-composant) +7. [Exemple TypeScript](#exemple-typescript) + +--- + +## Installation + +Installez l'encapsuleur Stencil et le moteur tsParticles via npm : + +```bash +npm install @tsparticles/stencil tsparticles +``` + +Installez optionnellement un bundle de préréglage pour réduire la configuration manuelle : + +```bash +npm install @tsparticles/slim +``` + +--- + +## Enregistrement des éléments personnalisés + +Le package `@tsparticles/stencil` fournit une fonction `defineCustomElements` qui enregistre l'élément personnalisé `` auprès du navigateur. Appelez-la une fois avant d'utiliser le composant n'importe où dans votre application. + +```tsx +import { defineCustomElements } from "@tsparticles/stencil/loader"; + +// Enregistrer l'élément +defineCustomElements(); +``` + +Pour les projets Stencil utilisant le chargement paresseux, appelez-la dans `componentWillLoad` ou dans le composant racine de votre application pour garantir que l'élément est disponible avant le rendu. + +--- + +## Utilisation de base + +Une fois l'élément personnalisé enregistré, vous pouvez utiliser `` dans votre JSX avec une prop `options` et un callback `init` pour charger les fonctionnalités moteur requises. + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +@Component({ tag: "my-particles" }) +export class MyParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## Initialisation du moteur + +La prop `init` reçoit l'instance du moteur et vous permet de charger les fonctionnalités dont vous avez besoin. C'est l'endroit recommandé pour appeler `loadSlim`, `loadFull` ou des plugins individuels de mise à jour/interaction. + +```tsx +import { loadSlim } from "@tsparticles/slim"; +import { loadFull } from "tsparticles"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// Option A : léger (cercles, mouvement de base, liaisons) +init={async engine => { await loadSlim(engine); }} + +// Option B : ensemble complet (toutes formes, effets, préréglages) +init={async engine => { await loadFull(engine); }} + +// Option C : préréglages (confetti, feux d'artifice, neige, étoiles) +init={async engine => { await loadConfettiPreset(engine); }} +``` + +L'instance du moteur est également accessible après l'initialisation via l'attribut `container-id`, vous permettant de contrôler le système de particules par programmation plus tard si nécessaire. + +--- + +## Configuration personnalisée + +Voici une configuration complète avec interactivité, types de formes multiples et modes survol/clic. + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const fullOptions: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { + color: "#0f0f23", + }, +}; + +@Component({ tag: "app-particles" }) +export class AppParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## Cycle de vie du composant + +Dans Stencil, le hook de cycle de vie recommandé pour la configuration unique est `componentWillLoad`. Utilisez-le pour enregistrer les éléments personnalisés et gérer l'état d'initialisation afin que le composant `` ne soit rendu que lorsque le moteur est préparé. + +```tsx +import { Component, h, State } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ tag: "app-root" }) +export class AppRoot { + @State() private engineReady = false; + + private options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { + enable: true, + speed: 1, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#1a1a2e" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.engineReady = true; + } + + render() { + return ( +
+

tsParticles + Stencil

+ {this.engineReady && ( + { + await loadSlim(engine); + }} + /> + )} +
+ ); + } +} +``` + +Utiliser `@State()` garantit que le composant se réaffiche lorsque le moteur devient prêt, et le rendu conditionnel empêche le conteneur de particules de se monter avant que l'élément personnalisé ne soit défini. + +--- + +## Exemple TypeScript + +Voici un composant d'application Stencil complet et typé qui intègre tsParticles avec le préréglage slim, l'interactivité au survol et un thème sombre personnalisé. + +```tsx +import { Component, h, State, Prop } from "@stencil/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ + tag: "app-home", + styleUrl: "app-home.css", + shadow: true, +}) +export class AppHome { + @State() private initialized = false; + + @Prop() readonly title: string = "Bienvenue"; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.initialized = true; + } + + private handleInit = async (engine: Engine): Promise => { + await loadSlim(engine); + }; + + private handleLoaded = async (container?: Container): Promise => { + this.container = container; + console.log("Conteneur de particules chargé :", container?.id); + }; + + render() { + return ( +
+

{this.title}

+

Propulsé par tsParticles et Stencil

+ + {this.initialized && ( + + )} +
+ ); + } +} +``` + +L'événement `particlesLoaded` se déclenche une fois la première image rendue, vous donnant accès à l'instance `Container` pour un contrôle programmatique (lecture, pause, arrêt, changement de thèmes). + +--- + +Vous avez maintenant tout ce qu'il faut pour intégrer tsParticles dans une application Stencil. Chaque exemple est autonome et prêt à être copié dans votre projet. diff --git a/websites/website/docs/fr/guides/svelte.md b/websites/website/docs/fr/guides/svelte.md new file mode 100644 index 00000000000..92cb83b52dd --- /dev/null +++ b/websites/website/docs/fr/guides/svelte.md @@ -0,0 +1,580 @@ +--- +title: Intégration Svelte +description: Guide étape par étape pour intégrer tsParticles dans des applications Svelte et SvelteKit en utilisant @tsparticles/svelte. +--- + +# Intégration Svelte + +Le package `@tsparticles/svelte` fournit un composant Svelte natif pour tsParticles. Ce guide couvre Svelte (avec Vite) et SvelteKit, incluant les options réactives, la gestion des événements et les instances multiples. + +--- + +## Installation + +```bash +npm install @tsparticles/svelte @tsparticles/engine +``` + +Pour le bundle complet ou les préréglages : + +```bash +npm install tsparticles +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +``` + +--- + +## Utilisation de base + +```svelte + + + +``` + +--- + +## Initialisation du moteur + +Passez un gestionnaire d'événement `on:init` pour charger les plugins et préréglages dont votre application a besoin : + +```svelte + + + +``` + +Alternativement, utilisez l'utilitaire `initParticlesEngine` avant le montage : + +```svelte + + +{#if ready} + +{/if} +``` + +--- + +## Effet Neige + +```bash +npm install @tsparticles/preset-snow +``` + +```svelte + + + +``` + +Personnalisez le comportement du préréglage en fusionnant des options supplémentaires : + +```svelte + +``` + +--- + +## Effet Étoiles + +```bash +npm install @tsparticles/preset-stars +``` + +```svelte + + + +``` + +--- + +## Particules interactives + +Ajoutez de l'interactivité au survol de la souris et au clic : + +```svelte + + + +``` + +--- + +## Gestion des événements + +```svelte + + +
+ + + +
+ + +``` + +| Événement | Détail | Se déclenche | +| -------------------- | ----------- | -------------------------------- | +| `on:init` | `Engine` | Après l'initialisation du moteur | +| `on:particlesLoaded` | `Container` | Lorsque le conteneur est prêt | + +--- + +## Exemple TypeScript + +Composant typé complet : + +```svelte + + + +``` + +--- + +## Options dynamiques + +Les options réactives mettent à jour les particules sans recréer l'instance : + +```svelte + + +
+ +
+ + +``` + +La déclaration réactive `$:` recalcule `options` à chaque changement de `color`, et le composant `Particles` récupère la nouvelle configuration automatiquement. + +--- + +## Instances multiples + +Affichez plusieurs systèmes de particules indépendants sur la même page : + +```svelte + + +
+
+ +
+
+ +
+
+``` + +Chaque composant `` reçoit son propre `id`, canvas et contexte moteur. + +--- + +## Utilisation avec SvelteKit + +Dans SvelteKit, le canvas nécessite l'environnement du navigateur. Désactivez le SSR pour le composant : + +```svelte + + +{#if Component} + +{/if} +``` + +Ou encapsulez l'importation dans un composant client-only. Pour SvelteKit 2+, vous pouvez également utiliser les exclusions SSR de `vite-plugin-svelte`. + +--- + +## Référence API + +| Prop | Type | Défaut | Description | +| --------- | ---------------- | --------------- | ------------------------------------- | +| `id` | `string` | `"tsparticles"` | ID de l'élément canvas | +| `options` | `ISourceOptions` | `{}` | Objet de configuration des particules | +| `url` | `string` | — | URL d'une configuration JSON distante | + +| Événement | Détail | Description | +| -------------------- | ----------- | ------------------------------------------------------------------------------- | +| `on:init` | `Engine` | Se déclenche quand le moteur est initialisé (utilisez pour charger des plugins) | +| `on:particlesLoaded` | `Container` | Se déclenche quand le conteneur est complètement prêt | + +--- + +## Dépannage + +- **Canvas non visible** — Assurez-vous que le conteneur parent a des dimensions explicites (`height: 100%`, `height: 100vh`, ou une valeur de pixels fixe). +- **`loadFull n'est pas une fonction`** — Vérifiez que `tsparticles` est installé et que vous importez `loadFull` depuis `tsparticles` (pas depuis `@tsparticles/engine`). +- **La réactivité ne fonctionne pas** — Assurez-vous que `options` est une variable réactive (`$:` ou `let` liée à une source réactive). Les valeurs `const` simples ne seront pas mises à jour. +- **SvelteKit écran blanc** — Importez `@tsparticles/svelte` dynamiquement ou utilisez la protection `browser` comme montré dans la section SvelteKit ci-dessus. +- **Erreurs TypeScript pour `event.detail`** — Utilisez les types `CustomEvent` et `CustomEvent` pour les gestionnaires d'événements. diff --git a/websites/website/docs/fr/guides/vanilla.md b/websites/website/docs/fr/guides/vanilla.md new file mode 100644 index 00000000000..3fc6110b44d --- /dev/null +++ b/websites/website/docs/fr/guides/vanilla.md @@ -0,0 +1,889 @@ +--- +title: Guide Vanilla JS +description: Guide complet pour intégrer tsParticles avec du JavaScript pur. +--- + +# Guide Vanilla JS + +## Table des matières + +1. [Pour commencer](#pour-commencer) +2. [Particules de base](#particules-de-base) +3. [Effet confetti](#effet-confetti) +4. [Effet feu d'artifice](#effet-feu-dartifice) +5. [Effet rubans](#effet-rubans) +6. [Effet neige](#effet-neige) +7. [Effet réseau / liaisons](#effet-réseau--liaisons) +8. [Effet étoiles](#effet-étoiles) +9. [Configuration personnalisée](#configuration-personnalisée) +10. [Conteneurs multiples](#conteneurs-multiples) +11. [Contrôles dynamiques](#contrôles-dynamiques) + +--- + +## Pour commencer + +### CDN (démarrage rapide) + +Ajoutez un `
` fictif et des balises script dans votre HTML. Vous avez besoin au moins du moteur et d'un bundle, et vous devez appeler le chargeur avant `tsParticles.load()`. + +```html + + + + + + tsParticles – Pour commencer + + + +
+ + + + + + +``` + +### npm + +```bash +npm install @tsparticles/engine @tsparticles/slim +``` + +Puis importez et utilisez-le : + +```javascript +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +(async () => { + await loadSlim(tsParticles); + + await tsParticles.load({ + id: "tsparticles", + options: { + /* ... */ + }, + }); +})(); +``` + +> **Remarque :** `@tsparticles/engine` seul n'affiche rien. Vous devez installer un bundle (`@tsparticles/slim` recommandé) ou des plugins individuels pour obtenir des formes visibles. + +--- + +## Particules de base + +Une configuration minimale qui affiche 100 particules avec une forme circulaire, des couleurs aléatoires et un mouvement doux. Dans la v4, les couleurs des particules sont définies via `paint` au lieu de l'ancienne propriété `color`. + +```html + + + + + + Particules de base + + + +
+ + + + + + +``` + +--- + +## Effet confetti + +Utilisez le bundle dédié `@tsparticles/confetti` pour une explosion festive avec un seul appel de fonction. + +```html + + + + + + Confetti + + + + + + + + + +``` + +--- + +## Effet feu d'artifice + +Un spectacle de feux d'artifice utilisant le bundle dédié `@tsparticles/fireworks` avec des effets sonores. + +```html + + + + + + Feux d'artifice + + + + + + + +``` + +--- + +## Effet rubans + +Utilisez le bundle dédié `@tsparticles/ribbons` pour des animations de rubans fluides qui réagissent à la position de la souris. + +```html + + + + + + Rubans + + + + + + + +``` + +--- + +## Effet neige + +Flocons de neige tombant doucement en utilisant le catalogue de préréglages `@tsparticles/configs`. + +```html + + + + + + Effet neige + + + +
+ + + + + + + +``` + +Alternative, en utilisant le paquet de préréglage autonome : + +```html + + + + +``` + +--- + +## Effet réseau / liaisons + +Un visuel classique de nœuds connectés avec interactivité de la souris. Le bundle `@tsparticles/slim` inclut l'interaction de liaisons et le mode d'attraction par la souris. + +```html + + + + + + Réseau / Liaisons + + + +
+ + + + + + +``` + +--- + +## Effet étoiles + +Un ciel étoilé utilisant le catalogue de préréglages `@tsparticles/configs`. + +```html + + + + + + Effet étoiles + + + +
+ + + + + + + +``` + +Alternative, en utilisant le paquet de préréglage autonome : + +```html + + + + +``` + +--- + +## Configuration personnalisée + +Construisez une configuration à partir de zéro avec un fond dégradé, des effets de survol interactifs et plusieurs types de formes en utilisant le bundle slim. + +```html + + + + + + Configuration personnalisée + + + +

Configuration personnalisée

+
+ + + + + + +``` + +--- + +## Conteneurs multiples + +Exécutez plusieurs instances de particules indépendantes sur la même page, chacune avec sa propre configuration. + +```html + + + + + + Conteneurs multiples + + + +
+
+
+
+ + + + + + +``` + +--- + +## Contrôles dynamiques + +Lancez, arrêtez, mettez en pause et changez de thème par programmation à l'exécution. + +```html + + + + + + Contrôles dynamiques + + + +
+
+ + + + + + +
+ + + + + + +``` + +--- + +Vous avez maintenant couvert tous les principaux modèles d'intégration Vanilla JS pour tsParticles v4. Chaque exemple est un fichier HTML autonome que vous pouvez ouvrir dans votre navigateur pour voir tsParticles en action. diff --git a/websites/website/docs/fr/guides/vue3.md b/websites/website/docs/fr/guides/vue3.md new file mode 100644 index 00000000000..9bcdcf95130 --- /dev/null +++ b/websites/website/docs/fr/guides/vue3.md @@ -0,0 +1,622 @@ +--- +title: Intégration Vue 3 +description: Guide étape par étape pour intégrer tsParticles dans des applications Vue 3 en utilisant @tsparticles/vue3. +--- + +# Intégration Vue 3 + +Le package `@tsparticles/vue3` fournit un composant et un système de plugin Vue 3 natifs pour tsParticles. Ce guide couvre tout, de la configuration de base aux modèles avancés comme le changement de thème dynamique et les préréglages personnalisés. + +--- + +## Installation + +```bash +npm install @tsparticles/vue3 @tsparticles/engine +``` + +Installez optionnellement un préréglage ou le bundle complet : + +```bash +# Bundle complet (toutes les fonctionnalités) +npm install tsparticles + +# Préréglages spécifiques +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars + +# Configurations utilitaires +npm install @tsparticles/configs +``` + +--- + +## Utilisation de base + +Enregistrez le plugin dans le point d'entrée de votre application, puis utilisez le composant `` n'importe où. + +### Entrée de l'application (`main.ts`) + +```typescript +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +const app = createApp(App); + +app.use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, +}); + +app.mount("#app"); +``` + +### Composant (`App.vue`) + +```vue + + + +``` + +--- + +## Utilisation de `particlesInit` avec le composant + +Si vous préférez ne pas utiliser le plugin global, passez un callback `init` directement : + +```vue + + + +``` + +--- + +## Événements + +Le composant émet plusieurs événements du cycle de vie : + +```vue + + + +``` + +--- + +## Effet Confetti + +Utilisez le préréglage confetti pour les célébrations : + +```bash +npm install @tsparticles/preset-confetti +``` + +```vue + + + +``` + +Pour une explosion unique, chargez le préréglage puis appelez `tsParticles.load()` par programmation dans une méthode. + +--- + +## Effet Feux d'artifice + +Le préréglage feux d'artifice crée des explosions de particules à fort impact : + +```bash +npm install @tsparticles/preset-fireworks +``` + +```vue + + + +``` + +> **Conseil :** Le préréglage feux d'artifice est intensif en ressources. Déclenchez-le sur une interaction utilisateur (ex. clic sur un bouton) en basculant un `v-if` lié au composant. + +--- + +## Effet Neige + +Simulez la chute de neige avec le préréglage neige : + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +--- + +## Particules interactives + +Ajoutez des modes d'interactivité au survol et au clic : + +```vue + + + +``` + +Modes d'interaction disponibles : `grab`, `repulse`, `bubble`, `connect`, `push`, `remove`, `trail`, `attract`, `light`. + +--- + +## Changement de thème + +Échangez dynamiquement les thèmes de particules à l'exécution en mettant à jour l'objet d'options réactif : + +```vue + + + +``` + +Alternativement, utilisez l'option intégrée [themes](https://particles.js.org/docs/interfaces/Options_Interfaces_IOptions.IOptions.html#themes) et la propriété `theme` du conteneur pour un changement sans configuration. + +--- + +## Préréglage personnalisé depuis @tsparticles/configs + +Le package `@tsparticles/configs` exporte des objets de configuration prêts à l'emploi : + +```bash +npm install @tsparticles/configs +``` + +```vue + + + +``` + +Parcourez les configurations disponibles dans le package `@tsparticles/configs` pour des mises en page prêtes à l'emploi. + +--- + +## Approches d'initialisation du moteur + +Il existe deux façons d'initialiser le moteur : + +### 1. Plugin global (recommandé) + +```typescript +// main.ts +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +createApp(App) + .use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, + }) + .mount("#app"); +``` + +Le moteur est alors disponible globalement et toutes les instances `` le partagent. + +### 2. Init au niveau du composant + +Passez un callback `:init` à chaque instance ``. Utile lorsque différents composants ont besoin de différents ensembles de plugins : + +```vue + +``` + +### 3. Provider Particles (Composition API) + +Utilisez le provider pour accéder au moteur par programmation : + +```vue + +``` + +--- + +## Exportations nommées + TypeScript + +Exemple TypeScript complet avec tous les éléments ensemble : + +```vue + + + +``` + +--- + +## Référence API + +| Prop | Type | Défaut | Description | +| --------- | ----------------------------------- | --------------- | ----------------------------------- | +| `id` | `string` | `"tsparticles"` | ID de l'élément canvas | +| `options` | `ISourceOptions` | `{}` | Configuration des particules | +| `init` | `(engine: Engine) => Promise` | — | Callback d'initialisation du moteur | +| `url` | `string` | — | URL pour charger une config JSON | + +| Événement | Payload | Description | +| ------------------- | ----------- | ---------------------------------------------- | +| `@particles-loaded` | `Container` | Se déclenche quand le conteneur est initialisé | +| `@particles-init` | `Engine` | Se déclenche après l'initialisation du moteur | + +--- + +## Dépannage + +- **Erreur : `tsparticles n'est pas défini`** — Assurez-vous que `tsparticles` (ou les préréglages dont vous avez besoin) sont chargés dans le callback `init` avant le rendu du composant. +- **Canvas non affiché** — Vérifiez que le conteneur parent a une hauteur non nulle. Ajoutez une règle CSS comme `#tsparticles { height: 100vh; }`. +- **Problèmes de performances** — Abaissez `fpsLimit`, réduisez `particles.number.value`, ou désactivez `detectRetina` sur les appareils bas de gamme. +- **SSR (Nuxt)** — Le composant `` est client-only. Encapsulez-le dans `` ou utilisez la directive `client:only`. diff --git a/websites/website/docs/fr/guides/webcomponents.md b/websites/website/docs/fr/guides/webcomponents.md new file mode 100644 index 00000000000..751bf6fce0e --- /dev/null +++ b/websites/website/docs/fr/guides/webcomponents.md @@ -0,0 +1,359 @@ +# Web Components + +Utilisez tsParticles avec les Web Components natifs via le package `@tsparticles/webcomponents`. Cette approche ne nécessite aucun framework — juste du JavaScript vanilla et des éléments personnalisés. + +## Installation + +### Via CDN + +Incluez le cœur tsParticles et le bundle Web Components : + +```html + + +``` + +### Via npm + Build + +```bash +npm install @tsparticles/webcomponents tsparticles +``` + +Importez ensuite dans votre bundle JavaScript : + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; +``` + +## Initialisation du moteur + +Avant que l'élément `` puisse être rendu, le moteur doit être initialisé avec les fonctionnalités dont vous avez besoin. Appelez `initParticlesEngine` avec un callback qui charge les plugins souhaités : + +```javascript +import { initParticlesEngine } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +> **Pourquoi `loadFull` ?** Il enregistre toutes les formes intégrées (cercle, carré, polygone, image, etc.), les interactions (survol, clic) et les mises à jour (opacité, taille, couleur, etc.). Pour un bundle plus petit, utilisez `tsparticles-slim` ou sélectionnez des plugins individuels. + +## Définition de l'élément personnalisé + +Après l'initialisation du moteur, enregistrez l'élément personnalisé `` : + +```javascript +import { defineParticlesElement } from "@tsparticles/webcomponents"; + +defineParticlesElement(); +``` + +Ceci enregistre la balise `web-particles` auprès du `CustomElementRegistry` du navigateur. Il est sûr d'appeler plusieurs fois — les enregistrements en double sont ignorés. + +## Utilisation de base + +Une fois que `initParticlesEngine` et `defineParticlesElement` ont été exécutés, utilisez l'élément directement en HTML : + +```html + + + + + + tsParticles Web Components + + + + + + + +``` + +## Configuration personnalisée + +L'élément `` accepte la configuration via la propriété `options` (objet JavaScript) ou via JSON dans l'attribut `options`. + +### Via une propriété JavaScript + +```javascript +const el = document.querySelector("web-particles"); +el.options = { + background: { color: "#000000" }, + fpsLimit: 60, + particles: { + color: { value: ["#ff0000", "#00ff00", "#0000ff"] }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { value: 60 }, + opacity: { value: 0.6 }, + shape: { type: ["circle", "square"] }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + repulse: { distance: 200 }, + push: { quantity: 4 }, + }, + }, +}; +``` + +### Via un attribut HTML (JSON) + +```html + +``` + +> Lorsque vous utilisez l'attribut `options`, la valeur doit être du JSON valide. L'assignation de propriété est préférée pour les configurations complexes. + +## Création dynamique + +Vous pouvez créer des éléments `` entièrement en JavaScript et les ajouter au DOM à tout moment : + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +defineParticlesElement(); + +function createParticles(container, config) { + const el = document.createElement("web-particles"); + el.id = "dynamic-particles"; + el.style.position = "absolute"; + el.style.width = "100%"; + el.style.height = "100%"; + el.style.top = "0"; + el.style.left = "0"; + el.options = config; + container.appendChild(el); + return el; +} + +// Utilisation +const particles = createParticles(document.body, { + background: { color: "#1a1a2e" }, + particles: { + number: { value: 100 }, + links: { enable: true, color: "#e94560" }, + move: { enable: true, speed: 1 }, + }, +}); +``` + +## Extension de l'élément personnalisé + +Vous pouvez sous-classer `ParticlesElement` pour créer votre propre élément personnalisé avec configuration intégrée : + +```javascript +import { initParticlesEngine, ParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +class MyParticlesBackground extends ParticlesElement { + constructor() { + super(); + this.style.position = "fixed"; + this.style.top = "0"; + this.style.left = "0"; + this.style.width = "100%"; + this.style.height = "100%"; + this.style.zIndex = "-1"; + } + + connectedCallback() { + this.options = { + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true, speed: 2 }, + }, + }; + super.connectedCallback(); + } +} + +customElements.define("my-particles-bg", MyParticlesBackground); +``` + +Utilisation : + +```html + +``` + +## Accès et contrôle du conteneur + +L'élément personnalisé expose l'instance `Container` de tsParticles pour un contrôle impératif : + +```javascript +const el = document.querySelector("web-particles"); + +// Accéder au conteneur (disponible après connectedCallback) +const container = el.container; +container?.pause(); +container?.play(); + +// Détruire et nettoyer +el.dispose(); +``` + +## Exemple complet + +Une page HTML complète utilisant le module Web Components avec des scripts CDN : + +```html + + + + + + Démo tsParticles Web Components + + + +
+

tsParticles + Web Components

+

Éléments personnalisés natifs, aucun framework requis.

+
+ + + + + + +``` + +## Référence API + +| Export / Propriété | Type | Description | +| ------------------------------- | ------------------------ | ---------------------------------------------------------------------- | +| `initParticlesEngine(callback)` | `function` | Initialise le moteur tsParticles avec des chargeurs de plugins | +| `defineParticlesElement()` | `function` | Enregistre l'élément personnalisé `` | +| `ParticlesElement` | `class` | Classe de base que vous pouvez étendre pour des éléments personnalisés | +| `element.options` | `ISourceOptions` | Obtenir/définir l'objet de configuration des particules | +| `element.container` | `Container \| undefined` | Référence en lecture seule au `Container` sous-jacent | +| `element.dispose()` | `function` | Détruire l'instance de particules et nettoyer les ressources | diff --git a/websites/website/docs/fr/guides/wordpress.md b/websites/website/docs/fr/guides/wordpress.md new file mode 100644 index 00000000000..30aaeafcb50 --- /dev/null +++ b/websites/website/docs/fr/guides/wordpress.md @@ -0,0 +1,314 @@ +--- +title: Guide WordPress +description: Guide complet pour intégrer tsParticles avec WordPress en utilisant le plugin, les blocs, les shortcodes et l'intégration de thème. +--- + +# Guide WordPress + +## Table des matières + +1. [Installation](#installation) +2. [Activation du plugin](#activation-du-plugin) +3. [Utilisation du widget et du bloc](#utilisation-du-widget-et-du-bloc) +4. [Utilisation du shortcode](#utilisation-du-shortcode) +5. [Configuration via filtre PHP](#configuration-via-filtre-php) +6. [Configuration personnalisée via filtre](#configuration-personnalisée-via-filtre) +7. [Intégration dans un thème](#intégration-dans-un-thème) + +--- + +## Installation + +Le plugin WordPress tsParticles est disponible via l'annuaire des plugins WordPress. Installez-le directement depuis votre tableau de bord WordPress. + +### Depuis l'administration WordPress + +1. Allez dans **Plugins → Ajouter** +2. Recherchez "tsParticles" +3. Cliquez sur **Installer maintenant** sur le plugin tsParticles +4. Cliquez sur **Activer** + +### Installation manuelle + +1. Téléchargez le ZIP du plugin depuis l'annuaire des plugins WordPress ou la [page des versions](https://github.com/tsparticles/wordpress/releases) +2. Allez dans **Plugins → Ajouter → Téléverser un plugin** +3. Choisissez le fichier ZIP et cliquez sur **Installer maintenant** +4. Cliquez sur **Activer** + +--- + +## Activation du plugin + +Une fois activé, le plugin enregistre : + +- Un **bloc Gutenberg** nommé "tsParticles" disponible dans l'inséreur de blocs +- Un **shortcode** `[tsparticles]` pour une utilisation dans l'éditeur classique ou les templates PHP personnalisés +- Un **filtre PHP** `tsparticles_options` pour que les développeurs puissent injecter une configuration par programmation +- Des ressources front-end (JavaScript et CSS) qui ne sont mises en file d'attente que lorsque le bloc ou le shortcode est présent sur la page + +Après activation, vous pouvez vérifier que le plugin fonctionne en visitant **Réglages → tsParticles** dans la barre latérale d'administration WordPress, où une page de réglages de base peut être disponible selon la version du plugin. + +--- + +## Utilisation du widget et du bloc + +Le plugin tsParticles ajoute un bloc Gutenberg personnalisé pour l'éditeur de blocs (WordPress 5.0+). + +### Ajout du bloc + +1. Modifiez n'importe quel article ou page avec l'éditeur de blocs (Gutenberg) +2. Cliquez sur le bouton **+** (Ajouter un bloc) +3. Recherchez "tsParticles" ou "Particles" +4. Cliquez sur le bloc **tsParticles** pour l'insérer + +### Paramètres du bloc + +Une fois inséré, le panneau d'inspection du bloc (sur le côté droit) fournit des réglages : + +- **ID du conteneur** — un ID HTML unique pour le conteneur de particules (défaut : `tsparticles`) +- **Largeur / Hauteur** — définissez des dimensions explicites ou utilisez le mode plein écran +- **Z-Index** — contrôle la superposition par rapport aux autres contenus +- **Configuration** — collez un objet JSON d'options pour personnaliser entièrement l'apparence des particules + +Pour les barres latérales de thème ou les zones de widgets qui ne prennent pas en charge les blocs, utilisez plutôt l'approche [Shortcode](#utilisation-du-shortcode). + +--- + +## Utilisation du shortcode + +Utilisez le shortcode `[tsparticles]` dans l'éditeur classique, les blocs HTML personnalisés, ou directement dans les fichiers template PHP pour intégrer des arrière-plans de particules n'importe où sur votre site. + +### Shortcode de base + +``` +[tsparticles] +``` + +Ceci affiche la configuration de particules par défaut (cercles flottants simples sur fond sombre). + +### Shortcode avec options + +Passez une configuration JSON directement dans le shortcode en utilisant l'attribut `options` : + +``` +[tsparticles options='{"particles":{"number":{"value":50},"color":{"value":"#ff0000"},"shape":{"type":"circle"},"opacity":{"value":0.5},"size":{"value":{"min":1,"max":3}},"move":{"enable":true,"speed":1,"outModes":{"default":"bounce"}}},"background":{"color":"#1a1a2e"}}'] +``` + +### Shortcode dans les templates PHP + +```php +// Dans le header.php ou footer.php de votre thème +echo do_shortcode('[tsparticles]'); +``` + +Ou avec des options personnalisées : + +```php +$options = [ + 'particles' => [ + 'number' => ['value' => 80], + 'color' => ['value' => '#00d4ff'], + 'shape' => ['type' => 'circle'], + 'links' => [ + 'enable' => true, + 'distance' => 150, + 'color' => '#00d4ff', + 'opacity' => 0.3, + ], + 'move' => [ + 'enable' => true, + 'speed' => 1.5, + 'outModes' => ['default' => 'bounce'], + ], + ], + 'background' => ['color' => '#0d1117'], +]; + +echo do_shortcode('[tsparticles options=\'' . wp_json_encode($options) . '\']'); +``` + +--- + +## Configuration via filtre PHP + +Le plugin expose un filtre `tsparticles_options` qui vous permet de remplacer ou d'étendre la configuration des particules depuis le fichier `functions.php` de votre thème ou un plugin personnalisé. C'est l'approche recommandée pour les développeurs car elle garde la configuration en PHP et évite le JSON en ligne. + +### Filtre de base + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + $options['background'] = ['color' => '#0d1117']; + $options['particles']['number']['value'] = 100; + $options['particles']['color']['value'] = '#00d4ff'; + $options['particles']['shape']['type'] = 'circle'; + $options['particles']['opacity']['value'] = 0.6; + $options['particles']['size']['value'] = ['min' => 2, 'max' => 5]; + $options['particles']['links']['enable'] = true; + $options['particles']['links']['distance'] = 150; + $options['particles']['links']['color'] = '#00d4ff'; + $options['particles']['links']['opacity'] = 0.3; + $options['particles']['move']['enable'] = true; + $options['particles']['move']['speed'] = 1.5; + $options['particles']['move']['outModes']['default'] = 'bounce'; + return $options; +}); +``` + +Ce filtre s'exécute avant le rendu du shortcode ou du bloc, donc toute instance de tsParticles sur la page reçoit la configuration personnalisée. + +--- + +## Configuration personnalisée via filtre + +Voici une configuration personnalisée complète qui démontre toute la puissance du filtre — incluant l'interactivité, les types de formes multiples et le support des thèmes. + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + + // Arrière-plan plein écran + $options['fullScreen'] = [ + 'enable' => true, + 'zIndex' => -1, + ]; + + $options['fpsLimit'] = 60; + + // Paramètres des particules + $options['particles'] = [ + 'number' => [ + 'value' => 60, + 'density' => ['enable' => true, 'width' => 800, 'height' => 800], + ], + 'color' => [ + 'value' => ['#ff6b6b', '#feca57', '#48dbfb', '#ff9ff3', '#54a0ff'], + ], + 'shape' => [ + 'type' => ['circle', 'triangle', 'polygon'], + 'options' => [ + 'polygon' => ['sides' => 6], + ], + ], + 'opacity' => [ + 'value' => ['min' => 0.4, 'max' => 0.8], + ], + 'size' => [ + 'value' => ['min' => 3, 'max' => 8], + ], + 'links' => [ + 'enable' => true, + 'distance' => 200, + 'color' => '#ffffff', + 'opacity' => 0.15, + 'width' => 1, + ], + 'move' => [ + 'enable' => true, + 'speed' => 2, + 'direction' => 'none', + 'random' => true, + 'straight' => false, + 'outModes' => ['default' => 'out'], + ], + ]; + + // Interactivité + $options['interactivity'] = [ + 'events' => [ + 'onHover' => ['enable' => true, 'mode' => 'attract'], + 'onClick' => ['enable' => true, 'mode' => 'repulse'], + ], + 'modes' => [ + 'attract' => ['distance' => 200, 'duration' => 0.4, 'factor' => 1], + 'repulse' => ['distance' => 200, 'duration' => 0.4], + ], + ]; + + // Arrière-plan + $options['background'] = [ + 'color' => '#0f0f23', + ]; + + // Support des thèmes — basculement en mode clair + $options['themes'] = [ + [ + 'name' => 'light', + 'default' => ['value' => false], + 'options' => [ + 'background' => ['color' => '#f0f0f5'], + 'particles' => [ + 'color' => ['value' => ['#e74c3c', '#2ecc71', '#3498db', '#f1c40f']], + 'links' => ['color' => '#333333', 'opacity' => 0.2], + ], + ], + ], + ]; + + return $options; +}); +``` + +--- + +## Intégration dans un thème + +Pour faire de tsParticles un arrière-plan persistant sur tout votre thème WordPress, ajoutez le shortcode ou un appel PHP direct dans le `header.php` ou `footer.php` de votre thème. + +### Arrière-plan dans l'en-tête + +```php + + +
+ +
+ +``` + +### Styles d'arrière-plan plein écran + +Ajoutez le CSS suivant au `style.css` de votre thème ou via `wp_add_inline_style` : + +```css +#tsparticles-background { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + z-index: -1; + pointer-events: none; +} + +/* Assurez-vous que le contenu apparaît au-dessus des particules */ +.site-content { + position: relative; + z-index: 1; +} +``` + +### Chargement conditionnel + +Pour charger tsParticles uniquement sur des pages spécifiques : + +```php +// Dans functions.php — mettre en file d'attente uniquement sur la page d'accueil +add_action('wp', function () { + if (is_front_page()) { + add_filter('tsparticles_options', function (array $options): array { + $options['particles']['number']['value'] = 120; + $options['particles']['color']['value'] = '#ffffff'; + $options['particles']['move']['speed'] = 0.8; + $options['background']['color'] = '#1a1a2e'; + return $options; + }); + } +}); +``` + +Combinez ceci avec le placement du bloc ou du shortcode pour un arrière-plan de particules performant et spécifique à une page. + +--- + +Vous avez maintenant tout ce qu'il faut pour intégrer tsParticles dans un site WordPress. Que vous préfériez l'éditeur de blocs, les shortcodes ou le contrôle PHP complet, chaque approche vous offre un arrière-plan de particules unique avec un effort minimal. diff --git a/websites/website/docs/guide/bundles-all.md b/websites/website/docs/guide/bundles-all.md index fb5c51173d4..981a525a385 100644 --- a/websites/website/docs/guide/bundles-all.md +++ b/websites/website/docs/guide/bundles-all.md @@ -1,21 +1,42 @@ -# All +# Bundle: All -`@tsparticles/all` loads all official features and is ideal for fast prototyping. +`@tsparticles/all` loads **everything** from the tsParticles repository: every shape, interaction, updater, effect, path, easing, plugin, and export. It's the largest bundle, meant for prototyping and demos. -## When to choose All +## Included features -- You want all features available immediately. -- You are exploring options quickly. -- Bundle size is less important than speed of setup. +Inherits everything from `tsparticles` (full) plus: + +**All shapes:** arrow, cards, cog, heart, infinity, matrix, path, ribbon, rounded-polygon, rounded-rect, spiral, squircle + +**All external interactions:** cannon, light, particle, pop, particles-repulse + +**All effects:** bubble, filter, particles, shadow, trail + +**All path generators:** branches, brownian, curl-noise, curves, fractal-noise, grid, levy, perlin-noise, polygon, random, simplex-noise, spiral, svg, zig-zag + +**All easings:** back, bounce, circ, cubic, elastic, expo, gaussian, linear, quad, quart, quint, sigmoid, sine, smoothstep + +**All color plugins:** HEX, HSL, RGB, HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH + +**All plugins:** absorbers, background-mask, canvas-mask, emitters (all shapes), easings (all), export-image, export-json, export-video, infection, manual-particles, motion, poisson-disc, polygon-mask, responsive, sounds, themes, trail, zoom + +**All updaters:** destroy, gradient, life, opacity, orbit, out-modes, paint, roll, rotate, size, tilt, twinkle, wobble + +## When to use + +- Rapid prototyping to explore possibilities +- Demos and showcases +- Development environments where size doesn't matter +- **Not recommended for production** — prefer more targeted bundles ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/all ``` -## Setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadAll } from "@tsparticles/all"; @@ -25,20 +46,48 @@ await loadAll(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { number: { value: 100 }, + shape: { type: "heart" }, move: { enable: true, speed: 2 }, }, }, }); ``` -## Common pitfalls +### CDN (script tags) + +```html + + + +``` + +## Difference between `tsparticles` and `@tsparticles/all` + +See the comparison table on the [bundles-full page](/guide/bundles-full) for the detailed breakdown. + +## Common mistakes -- Using it in production when a smaller focused bundle would be better. -- Calling `tsParticles.load(...)` before `loadAll(...)`. +- Using it in production — prefer `@tsparticles/slim` or `tsparticles` for smaller bundles. +- Calling `tsParticles.load()` before `loadAll(tsParticles)`. -## Related pages +## See also -- Overview: [`/guide/bundles`](/guide/bundles) -- Installation matrix: [`/guide/installation`](/guide/installation) +- [Bundle overview](/guide/bundles) +- [Installation guide](/guide/installation) diff --git a/websites/website/docs/guide/bundles-basic.md b/websites/website/docs/guide/bundles-basic.md index 6944cfe5c20..65d2e94a439 100644 --- a/websites/website/docs/guide/bundles-basic.md +++ b/websites/website/docs/guide/bundles-basic.md @@ -1,21 +1,46 @@ -# Basic +# Bundle: Basic -`@tsparticles/basic` is for extra-light setups where you need a minimal runtime. +`@tsparticles/basic` is the lightest bundle. Only includes the essentials: circles that move with animatable opacity and size. -## When to choose Basic +## Included features -- Bundle size is the top priority. -- You only need core effects. -- Advanced plugins are not required. +**Shapes:** circle + +**Updaters:** + +- paint (color) +- opacity +- out-modes (behavior when leaving the screen) +- size + +**Plugins:** + +- move +- blend (color blending) +- HEX, HSL, RGB color plugins + +**Not included:** + +- Mouse/touch interactions +- Particle links +- Other shapes (squares, stars, images, polygons, etc.) +- Emitters, absorbers, sounds +- Rotation, life, roll, tilt, wobble + +## When to use + +- Bundle size is your top priority +- You only need dots moving around +- No interactions or complex shapes needed ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/basic ``` -## Setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadBasic } from "@tsparticles/basic"; @@ -25,20 +50,48 @@ await loadBasic(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#ffffff" }, particles: { number: { value: 50 }, - move: { enable: true, speed: 1.5 }, + color: { value: ["#5bc0eb", "#fde74c", "#9bc53d"] }, + size: { + value: { min: 300, max: 400 }, + animation: { enable: true, speed: 100 }, + }, + move: { enable: true, speed: 10 }, }, }, }); ``` -## Common pitfalls +### CDN (script tags) + +```html + + + +``` + +## Common mistakes -- Expecting features that belong to plugins not included in basic. -- Calling `tsParticles.load(...)` before `loadBasic(...)`. +- Expecting features not included (e.g., `links`, mouse interactions) — these require higher bundles. +- Calling `tsParticles.load()` before `loadBasic(tsParticles)` — shapes and updaters aren't registered yet. +- Installing only `@tsparticles/engine` without a bundle — the engine alone draws nothing. -## Related pages +## See also -- Overview: [`/guide/bundles`](/guide/bundles) -- Installation matrix: [`/guide/installation`](/guide/installation) +- [Bundle overview](/guide/bundles) +- [Installation guide](/guide/installation) diff --git a/websites/website/docs/guide/bundles-confetti.md b/websites/website/docs/guide/bundles-confetti.md index e27efe070c4..c88579480ed 100644 --- a/websites/website/docs/guide/bundles-confetti.md +++ b/websites/website/docs/guide/bundles-confetti.md @@ -1,42 +1,83 @@ -# Confetti +# Bundle: Confetti -`@tsparticles/confetti` exposes a focused API for confetti effects with minimal setup. +`@tsparticles/confetti` provides a simplified API for creating confetti effects with a single function call. No need to interact with `tsParticles` directly. -## When to choose Confetti +## Included features -- You want one-call celebratory effects. -- You do not need to wire the engine manually. -- You prefer a compact API for UI events. +**Shapes:** circle, heart, cards (French suits: hearts, diamonds, clubs, spades), emoji, images, polygon, square, star + +**Internal plugins:** emitters, motion (respects user's reduced motion preference) + +**Updaters:** life, roll, rotate, tilt, wobble + +**API:** `confetti(options)` or `confetti(canvasId, options)` + +## When to use + +- "Congratulations!" or "Happy Birthday!" button +- Quick celebration effect +- You don't want to configure the engine manually ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/confetti ``` -## Setup example - ```ts import { confetti } from "@tsparticles/confetti"; +// Basic effect await confetti({ - count: 80, - spread: 60, + particleCount: 100, + spread: 70, + origin: { x: 0.5, y: 0.5 }, }); -await confetti("canvas-id", { - count: 50, +// On a specific canvas +await confetti("my-canvas-id", { + particleCount: 50, angle: 90, spread: 45, + colors: ["#ff0000", "#00ff00", "#0000ff"], }); ``` -## Common pitfalls +### CDN (script tag) + +```html + + +``` + +### Main parameters + +| Parameter | Type | Default | Description | +| --------------- | -------- | ------------ | ---------------------------------------------------- | +| `particleCount` | number | 50 | Number of confetti pieces | +| `spread` | number | 60 | Spread angle (degrees) | +| `angle` | number | 90 | Direction (degrees, 90 = down) | +| `startVelocity` | number | 30 | Initial velocity | +| `colors` | string[] | — | Confetti colors | +| `origin` | { x, y } | { 0.5, 0.5 } | Origin point (0-1) | +| `drift` | number | 0 | Horizontal drift | +| `shapes` | string[] | — | Shapes: "circle", "heart", "square", "star", "cards" | + +## Common mistakes -- Assuming `tsParticles` is exported from `@tsparticles/confetti`. -- Reusing the same canvas id unintentionally. +- Thinking `tsParticles` is exported by `@tsparticles/confetti` — it is not. +- Reusing the same canvas ID unintentionally. +- Calling `confetti` in a loop without managing performance — use a reasonable interval or stop the animation when done. -## Related pages +## See also -- Overview: [`/guide/bundles`](/guide/bundles) -- Playground bundles: [`/playground/bundles`](/playground/bundles) +- [Bundle overview](/guide/bundles) +- [Fireworks bundle](/guide/bundles-fireworks) diff --git a/websites/website/docs/guide/bundles-fireworks.md b/websites/website/docs/guide/bundles-fireworks.md index 68d38deb052..57ea7f2a3d1 100644 --- a/websites/website/docs/guide/bundles-fireworks.md +++ b/websites/website/docs/guide/bundles-fireworks.md @@ -1,44 +1,81 @@ -# Fireworks +# Bundle: Fireworks -`@tsparticles/fireworks` exposes a focused API for fireworks effects with minimal setup. +`@tsparticles/fireworks` provides a simplified API for creating fireworks effects with a single function call. Supports sounds, custom colors, and instance control (pause/play). -## When to choose Fireworks +## Included features -- You want one-call fireworks animations. -- You do not need direct engine wiring. -- You prefer a compact API for celebratory moments. +**Shapes:** line, circle (from basic) + +**Internal plugins:** emitters, emitters-shape-square, blend (blending), sounds + +**Updaters:** destroy, life, paint, rotate + +**API:** `fireworks(options)` — returns a controllable instance + +## When to use + +- New Year or celebration effect +- Celebration UI +- You don't want to configure the engine manually ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/fireworks ``` -## Setup example - ```ts import { fireworks } from "@tsparticles/fireworks"; +// Basic effect const instance = await fireworks({ - colors: ["#ffffff", "#ff0000"], - sounds: false, + colors: ["#ffffff", "#ff0000", "#00ff00", "#0000ff"], + sounds: true, }); +// Instance control instance?.pause(); instance?.play(); -await fireworks("canvas-id", { +// On a specific canvas +await fireworks("my-canvas", { rate: 3, speed: { min: 10, max: 25 }, + sounds: false, }); ``` -## Common pitfalls +### CDN (script tag) + +```html + + +``` + +### Main parameters + +| Parameter | Type | Default | Description | +| ------------ | ------------ | ------- | -------------------- | +| `colors` | string[] | — | Explosion colors | +| `rate` | number | — | Fireworks per second | +| `speed` | { min, max } | — | Particle speed | +| `sounds` | boolean | true | Enable sound effects | +| `gravity` | number | — | Gravity (default: 0) | +| `opacity` | number | — | Opacity (0-1) | +| `brightness` | { min, max } | — | Explosion brightness | + +## Common mistakes -- Assuming `tsParticles` is exported from `@tsparticles/fireworks`. -- Calling `fireworks(...)` repeatedly without managing the returned instance. +- Thinking `tsParticles` is exported by `@tsparticles/fireworks` — it is not. +- Calling `fireworks()` in a loop without managing the instance — the effect is already continuous. +- Not stopping the instance when leaving the page — call `instance?.pause()` or `instance?.stop()`. -## Related pages +## See also -- Overview: [`/guide/bundles`](/guide/bundles) -- Playground bundles: [`/playground/bundles`](/playground/bundles) +- [Bundle overview](/guide/bundles) +- [Confetti bundle](/guide/bundles-confetti) diff --git a/websites/website/docs/guide/bundles-full.md b/websites/website/docs/guide/bundles-full.md index 2e21dace10e..3ed54fd4955 100644 --- a/websites/website/docs/guide/bundles-full.md +++ b/websites/website/docs/guide/bundles-full.md @@ -1,21 +1,48 @@ -# tsparticles (Full) +# Bundle: tsparticles (Full) -`tsparticles` is the full bundle and includes a broad set of official features with one loader. +`tsparticles` (npm: `tsparticles`, loader: `loadFull`) is the official full bundle. Includes everything from Slim plus emitters, absorbers, text shapes, and advanced animations (wobble, roll, tilt, twinkle, destroy). -## When to choose tsparticles (Full) +## Included features -- You need many official features without manually selecting plugins. -- You want a complete production-ready baseline before fine-tuning. -- You prefer engine control through the `tsParticles` API. +Inherits everything from `@tsparticles/slim` plus: + +**Additional shapes:** text (with custom fonts) + +**Additional external interactions:** + +- drag (drag particles with mouse) +- trail (particle trail behind mouse) + +**Additional updaters:** + +- destroy (particle destruction animation) +- roll (rolling) +- tilt (3D tilt) +- twinkle (intermittent sparkle) +- wobble (oscillation) + +**Plugins:** + +- absorbers (black holes that suck in particles) +- emitters (continuous particle sources) +- emitters-shape-circle, emitters-shape-square (emitter shapes) + +## When to use + +- Need emitters (particles spawning continuously) +- Need absorbers (particles being sucked in) +- Need text shapes with custom fonts +- Need advanced animations (wobble, tilt, roll, twinkle) +- Good stepping stone before going to individual plugins ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine tsparticles ``` -## Setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadFull } from "tsparticles"; @@ -25,20 +52,65 @@ await loadFull(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { - number: { value: 100 }, - move: { enable: true, speed: 2 }, + number: { value: 50 }, + shape: { type: "text", options: { text: ["🔥", "✨", "⭐"] } }, + size: { value: 24 }, + move: { enable: true, speed: 1 }, + wobble: { enable: true, distance: 10 }, + }, + emitters: { + direction: "top", + rate: { quantity: 2, delay: 0.3 }, }, }, }); ``` -## Common pitfalls +### CDN (script tags) + +```html + + + +``` + +## Difference between `tsparticles` and `@tsparticles/all` + +| Aspect | `tsparticles` (full) | `@tsparticles/all` | +| ------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| Size | Moderate | Very large | +| Shapes | circle, square, star, polygon, line, image, emoji, text | All shapes (heart, cards, arrow, spiral, cog, rounded-rect, etc.) | +| Interactions | Slim + drag + trail | All (cannon, light, pop, particle, repulse) | +| Paths | Quad easing only | 14 path generators | +| Effects | None | 5 effects (bubble, filter, shadow, etc.) | +| Exports | None | Image, JSON, Video | +| Extra plugins | absorbers, emitters | All (sounds, themes, trail, zoom, polygon-mask, canvas-mask, background-mask, etc.) | +| Easing | Quad | 15 easings | + +## Common mistakes -- Calling `tsParticles.load(...)` before `loadFull(...)`. -- Assuming this is the same package as `@tsparticles/all` (they are different bundles). +- Confusing `tsparticles` with `@tsparticles/all` — they are different packages. +- Calling `tsParticles.load()` before `loadFull(tsParticles)`. +- The npm package is `tsparticles` (not `@tsparticles/full`), the loader is `loadFull`. -## Related pages +## See also -- Overview: [`/guide/bundles`](/guide/bundles) -- Installation matrix: [`/guide/installation`](/guide/installation) +- [Bundle overview](/guide/bundles) +- [Installation guide](/guide/installation) diff --git a/websites/website/docs/guide/bundles-particles.md b/websites/website/docs/guide/bundles-particles.md index a851c41651d..502160e1baa 100644 --- a/websites/website/docs/guide/bundles-particles.md +++ b/websites/website/docs/guide/bundles-particles.md @@ -1,51 +1,98 @@ -# Particles +# Bundle: Particles -`@tsparticles/particles` exposes a focused API for simple particles backgrounds. +`@tsparticles/particles` provides a simplified API for creating interactive particle backgrounds. A richer alternative to `@tsparticles/basic` with a dedicated API instead of manual engine configuration. -## When to choose Particles +## Included features -- You want a quick particles background API. -- You do not need direct engine setup for every feature. -- You prefer a compact, app-like API. +**Shapes:** circle (from basic) + +**Internal plugins:** interactivity (links, collisions) + +**Interactions:** links (particle connections), collisions + +**API:** `particles(options)` or `particles(canvasId, options)` + +## When to use + +- Particle background for a website +- Background with particle links (node-style effect) +- You don't want to configure the engine manually ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/particles ``` -## Setup - ```ts import { particles } from "@tsparticles/particles"; -const instance = await particles({ +// Background with links +await particles({ count: 120, - color: "#00f", links: true, - linksColor: "#0ff", - linksLength: 140, - radius: 4, + color: "#ffffff", + linksColor: "#00d8ff", + radius: 3, + speed: 2, + opacity: 0.8, +}); + +// On a specific canvas +await particles("my-canvas", { + count: 80, shape: ["circle", "square"], + links: true, }); -instance?.pause(); -instance?.play(); +// With custom colors +await particles({ + count: 100, + color: ["#ff6b6b", "#4ecdc4", "#45b7d1"], + links: false, +}); ``` -Custom canvas: +### CDN (script tag) -```ts -const canvas = document.getElementById("my-canvas") as HTMLCanvasElement; -await particles.create(canvas, { links: true }); +```html + + ``` -## Common pitfalls +### Main parameters + +| Parameter | Type | Default | Description | +| ------------ | ------------------ | ---------- | ------------------- | +| `count` | number | 50 | Number of particles | +| `radius` | number | 3 | Particle radius | +| `speed` | number | 2 | Movement speed | +| `opacity` | number | 0.8 | Opacity (0-1) | +| `color` | string \| string[] | "#ffffff" | Particle color(s) | +| `links` | boolean | false | Show links | +| `linksColor` | string | "#ffffff" | Link color | +| `linksWidth` | number | 1 | Link thickness | +| `shape` | string[] | ["circle"] | Particle shapes | + +## Common mistakes -- Assuming `tsParticles` is exported from `@tsparticles/particles`. -- Reusing the same id unintentionally. +- Thinking `tsParticles` is exported by `@tsparticles/particles` — it is not. +- Reusing the same canvas ID unintentionally. +- Expecting advanced shapes (stars, polygons) — the particles bundle is based on basic and only uses circles. -## Related pages +## See also -- Overview: [`/guide/bundles`](/guide/bundles) -- Playground bundles: [`/playground/bundles`](/playground/bundles) +- [Bundle overview](/guide/bundles) +- [Getting started](/guide/getting-started) diff --git a/websites/website/docs/guide/bundles-slim.md b/websites/website/docs/guide/bundles-slim.md index de5feff536d..9bb528f2528 100644 --- a/websites/website/docs/guide/bundles-slim.md +++ b/websites/website/docs/guide/bundles-slim.md @@ -1,21 +1,61 @@ -# Slim +# Bundle: Slim -`@tsparticles/slim` is the recommended default for most projects. +`@tsparticles/slim` is the recommended bundle for most projects. Includes everything needed for modern particle animations with mouse interactions, multiple shapes, and particle links. -## When to choose Slim +## Included features -- You want a great size/features balance. -- You use the `tsParticles` engine API directly. -- You need common shapes/interactions without loading everything. +Inherits everything from `@tsparticles/basic` plus: + +**Shapes:** circle, square, star, polygon, line, image, emoji + +**External interactions (mouse/touch):** + +- attract +- bounce +- bubble +- connect +- destroy +- grab +- parallax +- pause +- push +- remove +- repulse +- slow + +**Particle interactions:** + +- attract +- collisions +- links (particle connections) + +**Additional updaters:** + +- life (lifecycle) +- rotate + +**Plugins:** + +- interactivity +- easing-quad +- HEX, HSL, RGB color plugins + +## When to use + +- Recommended starting point for most projects +- Need multiple shapes (circles, stars, polygons, images) +- Need mouse interactions (click, hover, bubble, repulse) +- Need particle links +- Good balance between bundle size and features ## Installation +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/slim ``` -## Setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; @@ -25,21 +65,47 @@ await loadSlim(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#0b1020" }, particles: { number: { value: 80 }, + links: { enable: true, distance: 150 }, move: { enable: true, speed: 2 }, - links: { enable: true }, + shape: { type: ["circle", "star", "square"] }, }, }, }); ``` -## Common pitfalls +### CDN (script tags) + +```html + + + +``` + +## Common mistakes -- Calling `tsParticles.load(...)` before `loadSlim(...)`. -- Mixing package versions across engine/plugins. +- Calling `tsParticles.load()` before `loadSlim(tsParticles)`. +- Mixing different versions between engine and bundle — keep them aligned. +- Expecting features from higher bundles (emitters, absorbers, text, wobble) — need `tsparticles` (full) or individual plugins. -## Related pages +## See also -- Overview: [`/guide/bundles`](/guide/bundles) -- Installation matrix: [`/guide/installation`](/guide/installation) +- [Bundle overview](/guide/bundles) +- [Installation guide](/guide/installation) diff --git a/websites/website/docs/guide/bundles.md b/websites/website/docs/guide/bundles.md index 7ba92425427..ac339c982d9 100644 --- a/websites/website/docs/guide/bundles.md +++ b/websites/website/docs/guide/bundles.md @@ -1,104 +1,184 @@ -# Bundles Guide - -This page helps you pick the right `tsParticles` bundle and set it up quickly. - -## Package comparison - -| Package | Best for | Setup style | -| ------------------------ | --------------------------------------------- | ---------------------------------------------- | -| `@tsparticles/basic` | Extra-light setups | `tsParticles` + `await loadBasic(tsParticles)` | -| `@tsparticles/slim` | Most websites/apps | `tsParticles` + `await loadSlim(tsParticles)` | -| `tsparticles` | Full official feature set with engine control | `tsParticles` + `await loadFull(tsParticles)` | -| `@tsparticles/all` | Full features, fastest prototyping | `tsParticles` + `await loadAll(tsParticles)` | -| `@tsparticles/confetti` | One-call confetti effects | `await confetti(options)` | -| `@tsparticles/fireworks` | One-call fireworks effects | `await fireworks(options)` | -| `@tsparticles/particles` | Simple particles background API | `await particles(options)` | -| `@tsparticles/ribbons` | One-call ribbons effects | `await ribbons(options)` | - -## Bundle guides - -- Basic: [`/guide/bundles-basic`](/guide/bundles-basic) -- Slim: [`/guide/bundles-slim`](/guide/bundles-slim) -- tsparticles (Full): [`/guide/bundles-full`](/guide/bundles-full) -- All: [`/guide/bundles-all`](/guide/bundles-all) -- Confetti: [`/guide/bundles-confetti`](/guide/bundles-confetti) -- Fireworks: [`/guide/bundles-fireworks`](/guide/bundles-fireworks) -- Particles: [`/guide/bundles-particles`](/guide/bundles-particles) -- Ribbons (demo + docs): [`/demos/recipes/ribbons`](/demos/recipes/ribbons) · - -## Installation - -Install the package path that matches your use case. - -```bash -pnpm add @tsparticles/engine @tsparticles/basic -pnpm add @tsparticles/engine @tsparticles/slim -pnpm add @tsparticles/engine tsparticles -pnpm add @tsparticles/engine @tsparticles/all -pnpm add @tsparticles/confetti -pnpm add @tsparticles/fireworks -pnpm add @tsparticles/particles -pnpm add @tsparticles/ribbons +# Bundle Guide + +tsParticles is modular. The `@tsparticles/engine` package contains only the core engine; to get visible effects you must register **shapes** (what to draw), **updaters** (how to animate), **interactions** (how to react to mouse/touch), and **plugins** (extra features). All this happens through **bundles**. + +## Bundle categories + +| Category | Bundle | API | +| --------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------- | +| Engine + loader | `@tsparticles/basic`, `@tsparticles/slim`, `tsparticles`, `@tsparticles/all` | `tsParticles.load({ id, options })` | +| Dedicated API | `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles`, `@tsparticles/ribbons` | `confetti({...})`, `fireworks({...})`, etc. | + +## Complete feature comparison + +Legend: ● = included, ○ = not included + +| Feature | basic | slim | full (`tsparticles`) | all | +| --------------------------------------------------------------------------------------------------- | ----- | ---- | -------------------- | ----------------- | +| **Shapes** | | | | | +| Circle | ● | ● | ● | ● | +| Square | ○ | ● | ● | ● | +| Star | ○ | ● | ● | ● | +| Polygon | ○ | ● | ● | ● | +| Line | ○ | ● | ● | ● | +| Image | ○ | ● | ● | ● | +| Emoji | ○ | ● | ● | ● | +| Text | ○ | ○ | ● | ● | +| Cards (suits) | ○ | ○ | ○ | ● | +| Heart | ○ | ○ | ○ | ● | +| Arrow | ○ | ○ | ○ | ● | +| Rounded rect | ○ | ○ | ○ | ● | +| Rounded polygon | ○ | ○ | ○ | ● | +| Spiral | ○ | ○ | ○ | ● | +| Squircle | ○ | ○ | ○ | ● | +| Cog | ○ | ○ | ○ | ● | +| Infinity | ○ | ○ | ○ | ● | +| Matrix | ○ | ○ | ○ | ● | +| Path | ○ | ○ | ○ | ● | +| Ribbon | ○ | ○ | ○ | ● | +| **External interactions (mouse/touch)** | | | | | +| Attract | ○ | ● | ● | ● | +| Bounce | ○ | ● | ● | ● | +| Bubble | ○ | ● | ● | ● | +| Connect | ○ | ● | ● | ● | +| Destroy | ○ | ● | ● | ● | +| Grab | ○ | ● | ● | ● | +| Parallax | ○ | ● | ● | ● | +| Pause | ○ | ● | ● | ● | +| Push | ○ | ● | ● | ● | +| Remove | ○ | ● | ● | ● | +| Repulse | ○ | ● | ● | ● | +| Slow | ○ | ● | ● | ● | +| Drag | ○ | ○ | ● | ● | +| Trail | ○ | ○ | ● | ● | +| Cannon | ○ | ○ | ○ | ● | +| Particle | ○ | ○ | ○ | ● | +| Pop | ○ | ○ | ○ | ● | +| Light | ○ | ○ | ○ | ● | +| **Particle interactions** | | | | | +| Links | ○ | ● | ● | ● | +| Collisions | ○ | ● | ● | ● | +| Attract | ○ | ● | ● | ● | +| Repulse | ○ | ○ | ○ | ● | +| **Updaters (animations)** | | | | | +| Opacity | ● | ● | ● | ● | +| Size | ● | ● | ● | ● | +| Out modes | ● | ● | ● | ● | +| Paint (color) | ● | ● | ● | ● | +| Rotate | ○ | ● | ● | ● | +| Life | ○ | ● | ● | ● | +| Destroy | ○ | ○ | ● | ● | +| Roll | ○ | ○ | ● | ● | +| Tilt | ○ | ○ | ● | ● | +| Twinkle | ○ | ○ | ● | ● | +| Wobble | ○ | ○ | ● | ● | +| Gradient | ○ | ○ | ○ | ● | +| Orbit | ○ | ○ | ○ | ● | +| **Plugins** | | | | | +| Move | ● | ● | ● | ● | +| Blend | ● | ● | ● | ● | +| Emitters | ○ | ○ | ● | ● | +| Absorbers | ○ | ○ | ● | ● | +| Sounds | ○ | ○ | ○ | ● | +| Motion (user prefs) | ○ | ○ | ○ | ● | +| Themes | ○ | ○ | ○ | ● | +| Polygon mask | ○ | ○ | ○ | ● | +| Canvas mask | ○ | ○ | ○ | ● | +| Background mask | ○ | ○ | ○ | ● | +| Export (image, json, video) | ○ | ○ | ○ | ● | +| Manual particles | ○ | ○ | ○ | ● | +| Responsive | ○ | ○ | ○ | ● | +| Trail | ○ | ○ | ○ | ● | +| Zoom | ○ | ○ | ○ | ● | +| Poisson disc | ○ | ○ | ○ | ● | +| **Paths** | | | | | +| Any path | ○ | ○ | ○ | ● (14 generators) | +| **Effects** | | | | | +| Bubble, Filter, Shadow, etc. | ○ | ○ | ○ | ● (5 effects) | +| **Easing** | | | | | +| Quad | ○ | ● | ● | ● | +| Back, Bounce, Circ, Cubic, Elastic, Expo, Gaussian, Linear, Quart, Quint, Sigmoid, Sine, Smoothstep | ○ | ○ | ○ | ● | +| **Color plugins** | | | | | +| HEX, HSL, RGB | ● | ● | ● | ● | +| HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH | ○ | ○ | ○ | ● | + +### Dedicated API bundles + +| Feature | confetti | fireworks | particles | ribbons | +| --------------- | --------------------------------------------------------- | ----------------------- | ------------------ | ---------------- | +| Shapes | circle, heart, cards, emoji, image, polygon, square, star | line | (from basic) | ribbon | +| Interactions | — | — | links + collisions | — | +| Special plugins | emitters, motion | emitters, sounds, blend | — | emitters, motion | +| API call | `confetti(opts)` | `fireworks(opts)` | `particles(opts)` | `ribbons(opts)` | + +## Selection guide + +```mermaid +flowchart TD + A[Need to start fast?] -->|Yes| B[Use a preset?] + A -->|No| C[What bundle size?] + B -->|Yes| D["@tsparticles/configs + @tsparticles/slim"] + B -->|No| E["Confetti? → @tsparticles/confetti"] + B -->|No| F["Fireworks? → @tsparticles/fireworks"] + B -->|No| G["Particle BG? → @tsparticles/particles"] + B -->|No| H["Ribbons? → @tsparticles/ribbons"] + C -->|"Minimal (circles only)"| I["@tsparticles/basic"] + C -->|"Medium (shapes + interactions)"| J["@tsparticles/slim"] + C -->|"Maximum (all features)"| K["tsparticles (loadFull)"] + C -->|"Whole repository"| L["@tsparticles/all"] ``` -Need CDN links and more package-manager variants? - -- See [`/guide/installation`](/guide/installation). - -## Setup examples - -### Engine + loader bundles (`basic`, `slim`, `full`, `all`) - -```ts -import { tsParticles } from "@tsparticles/engine"; -import { loadSlim } from "@tsparticles/slim"; - -await loadSlim(tsParticles); - -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - number: { value: 80 }, - move: { enable: true, speed: 2 }, - }, - }, -}); +**Rules of thumb:** + +1. Most projects start with `@tsparticles/slim`. +2. If bundle size is critical and you only need circles: `@tsparticles/basic`. +3. If you need emitters, absorbers, text, wobble/tilt/roll: `tsparticles` with `loadFull`. +4. For quick prototyping with all features: `@tsparticles/all`. +5. For targeted effects (confetti, fireworks, particle BG, ribbons) with minimal setup: dedicated API bundles. + +## Quick install + +| Bundle | npm command | Loader function | CDN URL | +| ------------------------ | ------------------------------------------------- | ------------------------ | -------------------------------------------------------------- | +| `@tsparticles/basic` | `pnpm add @tsparticles/engine @tsparticles/basic` | `loadBasic(tsParticles)` | `@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| `@tsparticles/slim` | `pnpm add @tsparticles/engine @tsparticles/slim` | `loadSlim(tsParticles)` | `@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| `tsparticles` (full) | `pnpm add @tsparticles/engine tsparticles` | `loadFull(tsParticles)` | `tsparticles@4/tsparticles.bundle.min.js` | +| `@tsparticles/all` | `pnpm add @tsparticles/engine @tsparticles/all` | `loadAll(tsParticles)` | `@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| `@tsparticles/confetti` | `pnpm add @tsparticles/confetti` | `confetti(opts)` | `@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| `@tsparticles/fireworks` | `pnpm add @tsparticles/fireworks` | `fireworks(opts)` | `@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| `@tsparticles/particles` | `pnpm add @tsparticles/particles` | `particles(opts)` | `@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| `@tsparticles/ribbons` | `pnpm add @tsparticles/ribbons` | `ribbons(opts)` | `@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | + +**Note:** for basic/slim/full/all bundles you MUST call `load*` before `tsParticles.load()`. CDN files expose the loader function globally but do NOT auto-call it. The confetti/fireworks/particles/ribbons bundles have self-contained APIs — call `confetti()`, `fireworks()`, etc. directly. + +CDN example for `@tsparticles/slim`: + +```html + + + ``` -For the other presets, swap only the loader import/function: +CDN example for `@tsparticles/confetti`: -- `@tsparticles/basic` -> `loadBasic` -- `tsparticles` -> `loadFull` -- `@tsparticles/all` -> `loadAll` - -### Focused APIs (`confetti`, `fireworks`, `particles`, `ribbons`) - -```ts -import { confetti } from "@tsparticles/confetti"; -import { fireworks } from "@tsparticles/fireworks"; -import { particles } from "@tsparticles/particles"; -import { ribbons } from "@tsparticles/ribbons"; - -await confetti({ count: 80, spread: 60 }); -await fireworks({ sounds: false }); -await particles({ count: 100, links: true }); -await ribbons({ count: 5, spread: 0 }); +```html + + ``` -These APIs are great when you want fast integration without manually wiring many engine plugins. - -## Practical selection rules - -1. Start with `@tsparticles/slim` in most projects. -2. Use `@tsparticles/basic` if bundle size is your top priority and features are simple. -3. Use `tsparticles` when you need a broad full-feature baseline with `loadFull`. -4. Use `@tsparticles/all` for prototyping or when you need many features immediately. -5. Use `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles`, or `@tsparticles/ribbons` when your UI needs one focused effect with minimal setup. +See also the [installation guide](/guide/installation) for CDN, npm, yarn, and file details. ## Related pages -- Playground focused bundles: [`/playground/bundles`](/playground/bundles) -- Getting started path: [`/guide/getting-started`](/guide/getting-started) -- Installation matrix: [`/guide/installation`](/guide/installation) -- Wrappers overview: [`/guide/wrappers`](/guide/wrappers) +- [Getting started](/guide/getting-started) +- [Installation guide](/guide/installation) +- [Presets catalog](/demos/presets) +- [Palettes catalog](/demos/palettes) +- [Shapes catalog](/demos/shapes) diff --git a/websites/website/docs/guide/color-formats.md b/websites/website/docs/guide/color-formats.md index 375ccf489f5..4025cc2ee69 100644 --- a/websites/website/docs/guide/color-formats.md +++ b/websites/website/docs/guide/color-formats.md @@ -1,6 +1,6 @@ # Color Formats -tsParticles accepts multiple color formats across options such as `background`, `particles.color`, and plugin settings. +tsParticles accepts multiple color formats across options such as `background`, `particles.paint`, and plugin settings. ## Common formats diff --git a/websites/website/docs/guide/getting-started.md b/websites/website/docs/guide/getting-started.md index 70c93bb0f8f..6f6095c0d09 100644 --- a/websites/website/docs/guide/getting-started.md +++ b/websites/website/docs/guide/getting-started.md @@ -1,106 +1,197 @@ # Getting Started -This path is the quickest reliable setup for `tsParticles` in 2026. +tsParticles is a JavaScript/TypeScript library for creating particle animations, confetti, fireworks, and more. It works in any modern browser and is available as both an npm package and via CDN with ` + + + + +
+ + + +``` + +> **Note**: even with CDN bundles you MUST call `loadSlim(tsParticles)` (or `loadBasic` / `loadFull` / `loadAll`) before `tsParticles.load()`. CDN bundles expose the loader function globally but do NOT auto-call it. + +Same pattern applies to `@tsparticles/basic` → `loadBasic`, `tsparticles` → `loadFull`, `@tsparticles/all` → `loadAll`. + +### Path C — Specialized bundles with dedicated API (confetti, fireworks, particles) + +Some bundles have their own simplified API, no need to use `tsParticles.load()`: + +```html + + + + + + + + + +``` + +Same for `fireworks()`, `particles()`, `ribbons()`. -- `@tsparticles/slim`: most apps should start here. -- `@tsparticles/basic`: smaller feature set for very light setups. -- `@tsparticles/all`: everything included, easiest for fast prototyping. +## Which bundle to choose? -If you need a focused API instead of direct `tsParticles` setup: +| Bundle | npm | When to use | +| ------------------------ | ------------------------ | ------------------------------------------------------------------------------------------------------------ | +| `@tsparticles/basic` | `loadBasic(tsParticles)` | Minimum: circles, movement, opacity, size. No interactions. | +| `@tsparticles/slim` | `loadSlim(tsParticles)` | **Recommended for most projects.** Adds interactions (click/hover), particle links, images, stars, polygons. | +| `tsparticles` | `loadFull(tsParticles)` | Full official feature set: emitters, absorbers, text shapes, roll, wobble, trail. | +| `@tsparticles/all` | `loadAll(tsParticles)` | **Everything** in the repo: every shape, interaction, effect, easing, path, export. Prototyping only. | +| `@tsparticles/confetti` | `confetti(options)` | Confetti in one function call. Dedicated API. | +| `@tsparticles/fireworks` | `fireworks(options)` | Fireworks in one function call. Dedicated API. | +| `@tsparticles/particles` | `particles(options)` | Simplified particle background. Dedicated API. | +| `@tsparticles/ribbons` | `ribbons(options)` | Ribbon effect. Dedicated API. | -- `@tsparticles/particles`: simplified particles background API -- `@tsparticles/confetti`: one-call confetti API -- `@tsparticles/fireworks`: one-call fireworks API +More details: [`/guide/bundles`](/guide/bundles). -## 5) Use presets/configs when you need speed +## Using presets -If you prefer prebuilt effects: +The `@tsparticles/configs` package contains dozens of ready-made configurations (absorbers, bubbles, snow, stars, gravity, collisions, etc.). ```bash -pnpm add @tsparticles/configs +pnpm add @tsparticles/engine @tsparticles/slim @tsparticles/configs +``` + +```ts +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import "@tsparticles/configs"; + +await loadSlim(tsParticles); + +await tsParticles.load({ + id: "tsparticles", + options: { preset: "snow" }, +}); ``` -Then load one config by key, like the [`demo/vite` app](https://github.com/tsparticles/tsparticles/blob/main/demo/vite/src/main.ts). +With CDN: -If you prefer preset-name based setups, use the official presets catalog in [`/demos/presets`](/demos/presets). +```html + + + + +``` -## Quick documentation map +## Quick references -- Root options: [`/options/`](/options/) -- Wrappers reference: [`/guide/wrappers`](/guide/wrappers) +- Options documentation: [`/options/`](/options/) +- Bundle guide: [`/guide/bundles`](/guide/bundles) - Presets catalog: [`/demos/presets`](/demos/presets) - Palettes catalog: [`/demos/palettes`](/demos/palettes) - Shapes catalog: [`/demos/shapes`](/demos/shapes) -- Migration from particles.js: [`/migrations/particles-js`](/migrations/particles-js) +- Framework wrappers: [`/guide/wrappers`](/guide/wrappers) - Color formats: [`/guide/color-formats`](/guide/color-formats) - Container lifecycle: [`/guide/container-lifecycle`](/guide/container-lifecycle) -- Plugins and customization: [`/guide/plugins-customization`](/guide/plugins-customization) +- Plugins & customization: [`/guide/plugins-customization`](/guide/plugins-customization) ## Troubleshooting -- Blank screen: verify `#tsparticles` exists before calling `tsParticles.load`. -- Missing feature: you likely need another plugin/package (shape, interaction, updater). -- Type errors on options: keep your packages aligned to the same major/minor version. +| Problem | Likely cause | Solution | +| ----------------------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| Blank screen, no particles | `#tsparticles` doesn't exist in the DOM when calling `tsParticles.load()` | Ensure the DIV exists before the script, or use `DOMContentLoaded` | +| Blank screen, no particles | Installed only `@tsparticles/engine` | Also install a bundle (`@tsparticles/slim`) or plugins — engine alone has no shapes to draw | +| "loadBasic/loadSlim/loadFull is not a function" error | Bundle not installed or wrong import | `pnpm add @tsparticles/slim` and import `{ loadSlim }` | +| Particles don't move | `move.enable` not set to `true` | Add `move: { enable: true, speed: 2 }` | +| Missing feature (e.g. links, collisions) | Chosen bundle doesn't include it | Switch to a richer bundle (`@tsparticles/slim` or `tsparticles`) or install the specific plugin | +| TypeScript type errors | Package versions out of sync | Keep engine and bundle on the same major/minor version | diff --git a/websites/website/docs/guide/installation.md b/websites/website/docs/guide/installation.md index 2ab8697fc05..a1e1b04bc47 100644 --- a/websites/website/docs/guide/installation.md +++ b/websites/website/docs/guide/installation.md @@ -1,109 +1,146 @@ # Installation -This page mirrors the installation matrix from the main `tsParticles` README. - -Source of truth: - ## Choose your path -- **Fast default**: `@tsparticles/engine` + `@tsparticles/slim` -- **Smaller custom runtime**: `@tsparticles/engine` + only required plugins -- **Focused APIs**: `@tsparticles/particles`, `@tsparticles/confetti`, `@tsparticles/fireworks`, or `@tsparticles/ribbons` -- **All features included**: `@tsparticles/all` - -## Hosting / CDN - -Use one of these providers (or self-host your built files). +| Scenario | Command | +| ------------------------- | ------------------------------------------------- | +| Quick start (recommended) | `pnpm add @tsparticles/engine @tsparticles/slim` | +| Minimal setup | `pnpm add @tsparticles/engine @tsparticles/basic` | +| Full feature set | `pnpm add @tsparticles/engine tsparticles` | +| Everything in the repo | `pnpm add @tsparticles/engine @tsparticles/all` | +| Confetti only | `pnpm add @tsparticles/confetti` | +| Fireworks only | `pnpm add @tsparticles/fireworks` | +| Particle background | `pnpm add @tsparticles/particles` | +| Ribbon effect | `pnpm add @tsparticles/ribbons` | -### jsDelivr +> **Important**: `@tsparticles/engine` alone draws nothing. You must always add a bundle (to load shapes and animations) or individual plugins. See the [bundle guide](/guide/bundles). -- -- -- -- -- -- -- -- +## npm -### cdnjs +```bash +# engine + slim (recommended for most projects) +npm install @tsparticles/engine @tsparticles/slim -- +# engine + basic (minimal) +npm install @tsparticles/engine @tsparticles/basic -### unpkg +# engine + full (tsparticles) +npm install @tsparticles/engine tsparticles -- -- -- -- -- -- -- -- +# engine + all +npm install @tsparticles/engine @tsparticles/all -## Package manager install +# Dedicated API bundles (no explicit engine needed) +npm install @tsparticles/confetti +npm install @tsparticles/fireworks +npm install @tsparticles/particles +npm install @tsparticles/ribbons +``` -### npm +## yarn ```bash -npm install @tsparticles/engine +yarn add @tsparticles/engine @tsparticles/slim +# ... same pattern for other bundles ``` -### yarn +## pnpm ```bash -yarn add @tsparticles/engine +pnpm add @tsparticles/engine @tsparticles/slim +# ... same pattern for other bundles ``` -### pnpm +## CDN (script tags) -```bash -pnpm add @tsparticles/engine -``` +All packages are available on jsDelivr, unpkg, and cdnjs. -## Import and require +### jsDelivr -```ts -const tsParticles = require("@tsparticles/engine"); +| Bundle | URL | +| -------------------------- | ------------------------------------------------------------------------------------------- | +| Engine | `https://cdn.jsdelivr.net/npm/@tsparticles/engine@4/tsparticles.engine.min.js` | +| Basic | `https://cdn.jsdelivr.net/npm/@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| Slim | `https://cdn.jsdelivr.net/npm/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| Full (`tsparticles`) | `https://cdn.jsdelivr.net/npm/tsparticles@4/tsparticles.bundle.min.js` | +| All | `https://cdn.jsdelivr.net/npm/@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| Confetti | `https://cdn.jsdelivr.net/npm/@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| Fireworks | `https://cdn.jsdelivr.net/npm/@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| Particles | `https://cdn.jsdelivr.net/npm/@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| Ribbons | `https://cdn.jsdelivr.net/npm/@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | +| particles.js compatibility | `https://cdn.jsdelivr.net/npm/@tsparticles/pjs@4/tsparticles.pjs.min.js` | -// or +### unpkg -import { tsParticles } from "@tsparticles/engine"; -``` +Same structure: `https://unpkg.com/{package-name}@{version}/{filename}` -## Minimal runtime setup (`@tsparticles/slim`) +Example: +`https://unpkg.com/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` + +### cdnjs + +`https://cdnjs.com/libraries/tsparticles` + +## Import examples + +### With bundler (ES module import) ```ts +// Engine + bundle loader import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; await loadSlim(tsParticles); +await tsParticles.load({ id: "tsparticles", options: { ... } }); +``` -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - move: { - enable: true, - }, - number: { - value: 60, - }, - }, - }, -}); +### With CommonJS (require) + +```ts +const { tsParticles } = require("@tsparticles/engine"); +const { loadSlim } = require("@tsparticles/slim"); + +(async () => { + await loadSlim(tsParticles); + await tsParticles.load({ id: "tsparticles", options: { ... } }); +})(); ``` -## Related pages +### With CDN (script tag) + +```html + + + + + + +``` -- [`/guide/getting-started`](/guide/getting-started) -- [`/guide/wrappers`](/guide/wrappers) -- [`/demos/presets`](/demos/presets) -- [`/migrations/particles-js`](/migrations/particles-js) +With dedicated API bundles: -## Legacy compatibility +```html + + +``` -If you are migrating legacy particles.js integrations, use the compatibility package: +## Related pages -- npm: -- jsDelivr: +- [Getting started](/guide/getting-started) +- [Bundle guide](/guide/bundles) +- [Framework wrappers](/guide/wrappers) diff --git a/websites/website/docs/guides/vanilla.md b/websites/website/docs/guides/vanilla.md index d2f8f344d10..c12fe20faf3 100644 --- a/websites/website/docs/guides/vanilla.md +++ b/websites/website/docs/guides/vanilla.md @@ -11,12 +11,13 @@ description: Complete guide for integrating tsParticles with plain JavaScript. 2. [Basic Particles](#basic-particles) 3. [Confetti Effect](#confetti-effect) 4. [Fireworks Effect](#fireworks-effect) -5. [Snow Effect](#snow-effect) -6. [Network / Links Effect](#network-links-effect) -7. [Stars Effect](#stars-effect) -8. [Custom Configuration](#custom-configuration) -9. [Multiple Containers](#multiple-containers) -10. [Dynamic Controls](#dynamic-controls) +5. [Ribbons Effect](#ribbons-effect) +6. [Snow Effect](#snow-effect) +7. [Network / Links Effect](#network-links-effect) +8. [Stars Effect](#stars-effect) +9. [Custom Configuration](#custom-configuration) +10. [Multiple Containers](#multiple-containers) +11. [Dynamic Controls](#dynamic-controls) --- @@ -24,7 +25,7 @@ description: Complete guide for integrating tsParticles with plain JavaScript. ### CDN (quick start) -Add a `
` placeholder and a script tag in your HTML: +Add a `
` placeholder and script tags in your HTML. You need at least the engine + a bundle, and you must call the loader before `tsParticles.load()`. ```html @@ -44,14 +45,19 @@ Add a `
` placeholder and a script tag in your HTML:
- + + @@ -60,27 +66,34 @@ Add a `
` placeholder and a script tag in your HTML: ### npm ```bash -npm install @tsparticles/engine +npm install @tsparticles/engine @tsparticles/slim ``` Then import and use it: ```javascript import { tsParticles } from "@tsparticles/engine"; - -tsParticles.load({ - id: "tsparticles", - options: { - /* ... */ - }, -}); +import { loadSlim } from "@tsparticles/slim"; + +(async () => { + await loadSlim(tsParticles); + + await tsParticles.load({ + id: "tsparticles", + options: { + /* ... */ + }, + }); +})(); ``` +> **Note:** `@tsparticles/engine` alone draws nothing. You must install a bundle (`@tsparticles/slim` recommended) or individual plugins to get visible shapes. + --- ## Basic Particles -A minimal configuration that renders 100 particles with a circular shape, random colours, and gentle movement. +A minimal configuration that renders 100 particles with a circular shape, random colours, and gentle movement. In v4, particle colors are set via `paint` instead of the old `color` property. ```html @@ -103,34 +116,55 @@ A minimal configuration that renders 100 particles with a circular shape, random
- + + @@ -140,7 +174,7 @@ A minimal configuration that renders 100 particles with a circular shape, random ## Confetti Effect -Use the built-in confetti preset for a celebratory burst. +Use the dedicated `@tsparticles/confetti` bundle for a celebratory burst with a single function call. ```html @@ -150,28 +184,21 @@ Use the built-in confetti preset for a celebratory burst. Confetti -
+ - - + @@ -182,7 +209,7 @@ Use the built-in confetti preset for a celebratory burst. ## Fireworks Effect -A fireworks show with particles exploding across the screen. +A fireworks show using the dedicated `@tsparticles/fireworks` bundle with sound effects. ```html @@ -199,23 +226,48 @@ A fireworks show with particles exploding across the screen. - - + + + +``` + +--- + +## Ribbons Effect + +Use the dedicated `@tsparticles/ribbons` bundle for flowing ribbon animations that react to mouse position. + +```html + + + + + + Ribbons + + + + + @@ -227,7 +279,7 @@ A fireworks show with particles exploding across the screen. ## Snow Effect -Gentle falling snowflakes using the snow preset. +Gentle falling snowflakes using the `@tsparticles/configs` preset catalog. ```html @@ -251,33 +303,49 @@ Gentle falling snowflakes using the snow preset.
- - + + + ``` +Alternatively, using the standalone preset package: + +```html + + + + +``` + --- -## Network Links Effect +## Network / Links Effect -A classic connected-nodes visual with mouse interactivity. +A classic connected-nodes visual with mouse interactivity. The `@tsparticles/slim` bundle includes the links interaction and mouse grab mode. ```html @@ -300,46 +368,53 @@ A classic connected-nodes visual with mouse interactivity.
- + + @@ -349,7 +424,7 @@ A classic connected-nodes visual with mouse interactivity. ## Stars Effect -A starry-night sky using the stars preset. +A starry-night sky using the `@tsparticles/configs` preset catalog. ```html @@ -373,33 +448,49 @@ A starry-night sky using the stars preset.
- - + + + ``` +Alternatively, using the standalone preset package: + +```html + + + + +``` + --- ## Custom Configuration -Build a configuration from scratch with a gradient background, interactive hover effects, and multiple shape types. +Build a configuration from scratch with a gradient background, interactive hover effects, and multiple shape types using the slim bundle. ```html @@ -431,73 +522,105 @@ Build a configuration from scratch with a gradient background, interactive hover

Custom Configuration

- + + @@ -543,77 +666,101 @@ Run multiple independent particle instances on the same page, each with its own
- + + @@ -678,16 +825,21 @@ Programmatically start, stop, pause, and switch themes at runtime.
- + + + + +``` + +## `tsparticles` और `@tsparticles/all` के बीच अंतर + +विस्तृत तुलना के लिए [bundles-full पेज](/hi/guide/bundles-full) पर तुलना तालिका देखें। + +## सामान्य गलतियाँ -- production में `all` इस्तेमाल करना जबकि smaller focused bundle बेहतर हो। -- `loadAll(...)` से पहले `tsParticles.load(...)` कॉल करना। +- प्रोडक्शन में इसका उपयोग करना — छोटे बंडलों के लिए `@tsparticles/slim` या `tsparticles` पसंद करें। +- `loadAll(tsParticles)` से पहले `tsParticles.load()` कॉल करना। -## Related pages +## यह भी देखें -- Overview: [`/guide/bundles`](/hi/guide/bundles) -- Installation matrix: [`/guide/installation`](/hi/guide/installation) +- [बंडल अवलोकन](/hi/guide/bundles) +- [इंस्टॉलेशन गाइड](/hi/guide/installation) diff --git a/websites/website/docs/hi/guide/bundles-basic.md b/websites/website/docs/hi/guide/bundles-basic.md index 4fc0907087f..286c517958d 100644 --- a/websites/website/docs/hi/guide/bundles-basic.md +++ b/websites/website/docs/hi/guide/bundles-basic.md @@ -1,21 +1,46 @@ # Bundle: Basic -`@tsparticles/basic` extra-light setups के लिए है, जहां runtime बहुत minimal रखना है। +`@tsparticles/basic` सबसे हल्का बंडल है। केवल आवश्यक चीज़ें शामिल करता है: सर्कल जो एनिमेटेबल ओपेसिटी और साइज़ के साथ चलते हैं। -## Basic कब चुनें +## शामिल सुविधाएँ -- bundle size आपकी top priority है। -- आपको सिर्फ core effects चाहिए। -- advanced plugins की जरूरत नहीं है। +**शेप:** circle + +**अपडेटर:** + +- paint (रंग) +- opacity +- out-modes (स्क्रीन छोड़ने पर व्यवहार) +- size + +**प्लगइन:** + +- move +- blend (रंग मिश्रण) +- HEX, HSL, RGB रंग प्लगइन + +**शामिल नहीं:** + +- माउस/टच इंटरैक्शन +- कण लिंक +- अन्य शेप (स्क्वेयर, स्टार, इमेज, पॉलीगॉन, आदि) +- एमिटर, एब्ज़ॉर्बर, साउंड +- रोटेशन, लाइफ, रोल, टिल्ट, वॉबल + +## कब उपयोग करें + +- बंडल आकार आपकी सर्वोच्च प्राथमिकता है +- आपको केवल घूमते हुए डॉट्स चाहिए +- किसी इंटरैक्शन या जटिल शेप की आवश्यकता नहीं ## इंस्टॉलेशन +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/basic ``` -## Setup example - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadBasic } from "@tsparticles/basic"; @@ -25,20 +50,48 @@ await loadBasic(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#ffffff" }, particles: { number: { value: 50 }, - move: { enable: true, speed: 1.5 }, + color: { value: ["#5bc0eb", "#fde74c", "#9bc53d"] }, + size: { + value: { min: 300, max: 400 }, + animation: { enable: true, speed: 100 }, + }, + move: { enable: true, speed: 10 }, }, }, }); ``` -## Common pitfalls +### CDN (script टैग) + +```html + + + +``` + +## सामान्य गलतियाँ -- उन features की उम्मीद करना जो basic bundle में शामिल नहीं हैं। -- `loadBasic(...)` से पहले `tsParticles.load(...)` कॉल करना। +- शामिल नहीं की गई सुविधाओं की अपेक्षा (जैसे `links`, माउस इंटरैक्शन) — इनके लिए उच्च बंडलों की आवश्यकता है। +- `loadBasic(tsParticles)` से पहले `tsParticles.load()` कॉल करना — शेप और अपडेटर अभी पंजीकृत नहीं हुए हैं। +- बंडल के बिना केवल `@tsparticles/engine` इंस्टॉल करना — इंजन अकेला कुछ नहीं बनाता। -## Related pages +## यह भी देखें -- Overview: [`/guide/bundles`](/hi/guide/bundles) -- Installation matrix: [`/guide/installation`](/hi/guide/installation) +- [बंडल अवलोकन](/hi/guide/bundles) +- [इंस्टॉलेशन गाइड](/hi/guide/installation) diff --git a/websites/website/docs/hi/guide/bundles-confetti.md b/websites/website/docs/hi/guide/bundles-confetti.md index 1121ff4974e..0130a07dd70 100644 --- a/websites/website/docs/hi/guide/bundles-confetti.md +++ b/websites/website/docs/hi/guide/bundles-confetti.md @@ -1,42 +1,83 @@ # Bundle: Confetti -`@tsparticles/confetti` minimal setup के साथ confetti effects के लिए focused API देता है। +`@tsparticles/confetti` एक सरलीकृत API प्रदान करता है जो एक फ़ंक्शन कॉल के साथ कॉनफ़ेटी प्रभाव बनाता है। सीधे `tsParticles` से बातचीत करने की आवश्यकता नहीं है। -## Confetti कब चुनें +## शामिल सुविधाएँ -- आपको one-call celebration effects चाहिए। -- आपको engine को manually wire नहीं करना। -- UI events के लिए compact API चाहिए। +**शेप:** circle, heart, cards (फ़्रेंच सूट: hearts, diamonds, clubs, spades), emoji, images, polygon, square, star + +**आंतरिक प्लगइन:** emitters, motion (उपयोगकर्ता की reduced motion प्राथमिकता का सम्मान करता है) + +**अपडेटर:** life, roll, rotate, tilt, wobble + +**API:** `confetti(options)` या `confetti(canvasId, options)` + +## कब उपयोग करें + +- "बधाई हो!" या "जन्मदिन मुबारक!" बटन +- त्वरित उत्सव प्रभाव +- आप मैन्युअल रूप से इंजन कॉन्फ़िगर नहीं करना चाहते ## इंस्टॉलेशन +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/confetti ``` -## Setup example - ```ts import { confetti } from "@tsparticles/confetti"; +// मूल प्रभाव await confetti({ - count: 80, - spread: 60, + particleCount: 100, + spread: 70, + origin: { x: 0.5, y: 0.5 }, }); -await confetti("canvas-id", { - count: 50, +// किसी विशिष्ट कैनवास पर +await confetti("my-canvas-id", { + particleCount: 50, angle: 90, spread: 45, + colors: ["#ff0000", "#00ff00", "#0000ff"], }); ``` -## Common pitfalls +### CDN (script टैग) + +```html + + +``` + +### मुख्य पैरामीटर + +| पैरामीटर | टाइप | डिफ़ॉल्ट | विवरण | +| --------------- | -------- | ------------ | ------------------------------------------------- | +| `particleCount` | number | 50 | कॉनफ़ेटी टुकड़ों की संख्या | +| `spread` | number | 60 | फैलाव कोण (डिग्री) | +| `angle` | number | 90 | दिशा (डिग्री, 90 = नीचे) | +| `startVelocity` | number | 30 | प्रारंभिक वेग | +| `colors` | string[] | — | कॉनफ़ेटी रंग | +| `origin` | { x, y } | { 0.5, 0.5 } | मूल बिंदु (0-1) | +| `drift` | number | 0 | क्षैतिज बहाव | +| `shapes` | string[] | — | शेप: "circle", "heart", "square", "star", "cards" | + +## सामान्य गलतियाँ -- मान लेना कि `@tsparticles/confetti` से `tsParticles` export होता है। -- एक ही canvas id को अनजाने में reuse करना। +- यह सोचना कि `@tsparticles/confetti` से `tsParticles` एक्सपोर्ट होता है — ऐसा नहीं है। +- अनजाने में उसी कैनवास ID का पुन: उपयोग करना। +- प्रदर्शन का प्रबंधन किए बिना लूप में `confetti` कॉल करना — उचित अंतराल का उपयोग करें या एनिमेशन समाप्त होने पर रोकें। -## Related pages +## यह भी देखें -- Overview: [`/guide/bundles`](/hi/guide/bundles) -- Playground bundles: [`/playground/bundles`](/hi/playground/bundles) +- [बंडल अवलोकन](/hi/guide/bundles) +- [आतिशबाज़ी बंडल](/hi/guide/bundles-fireworks) diff --git a/websites/website/docs/hi/guide/bundles-fireworks.md b/websites/website/docs/hi/guide/bundles-fireworks.md index 6d0e5d9ab71..4cc8ce6cea6 100644 --- a/websites/website/docs/hi/guide/bundles-fireworks.md +++ b/websites/website/docs/hi/guide/bundles-fireworks.md @@ -1,44 +1,81 @@ # Bundle: Fireworks -`@tsparticles/fireworks` minimal setup के साथ fireworks effects के लिए focused API देता है। +`@tsparticles/fireworks` एक सरलीकृत API प्रदान करता है जो एक फ़ंक्शन कॉल के साथ आतिशबाज़ी प्रभाव बनाता है। ध्वनि, कस्टम रंग और इंस्टेंस नियंत्रण (पॉज़/प्ले) का समर्थन करता है। -## Fireworks कब चुनें +## शामिल सुविधाएँ -- आपको one-call fireworks animations चाहिए। -- आपको direct engine wiring की जरूरत नहीं है। -- celebration moments के लिए compact API चाहिए। +**शेप:** line, circle (basic से) + +**आंतरिक प्लगइन:** emitters, emitters-shape-square, blend (मिश्रण), sounds + +**अपडेटर:** destroy, life, paint, rotate + +**API:** `fireworks(options)` — एक नियंत्रणीय इंस्टेंस लौटाता है + +## कब उपयोग करें + +- नए साल या उत्सव प्रभाव +- उत्सव UI +- आप मैन्युअल रूप से इंजन कॉन्फ़िगर नहीं करना चाहते ## इंस्टॉलेशन +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/fireworks ``` -## Setup example - ```ts import { fireworks } from "@tsparticles/fireworks"; +// मूल प्रभाव const instance = await fireworks({ - colors: ["#ffffff", "#ff0000"], - sounds: false, + colors: ["#ffffff", "#ff0000", "#00ff00", "#0000ff"], + sounds: true, }); +// इंस्टेंस नियंत्रण instance?.pause(); instance?.play(); -await fireworks("canvas-id", { +// किसी विशिष्ट कैनवास पर +await fireworks("my-canvas", { rate: 3, speed: { min: 10, max: 25 }, + sounds: false, }); ``` -## Common pitfalls +### CDN (script टैग) + +```html + + +``` + +### मुख्य पैरामीटर + +| पैरामीटर | टाइप | डिफ़ॉल्ट | विवरण | +| ------------ | ------------ | -------- | --------------------------- | +| `colors` | string[] | — | विस्फोट के रंग | +| `rate` | number | — | प्रति सेकंड आतिशबाज़ी | +| `speed` | { min, max } | — | कण गति | +| `sounds` | boolean | true | ध्वनि प्रभाव सक्षम करें | +| `gravity` | number | — | गुरुत्वाकर्षण (डिफ़ॉल्ट: 0) | +| `opacity` | number | — | अपारदर्शिता (0-1) | +| `brightness` | { min, max } | — | विस्फोट चमक | + +## सामान्य गलतियाँ -- मान लेना कि `@tsparticles/fireworks` से `tsParticles` export होता है। -- returned instance को manage किए बिना `fireworks(...)` बार-बार कॉल करना। +- यह सोचना कि `@tsparticles/fireworks` से `tsParticles` एक्सपोर्ट होता है — ऐसा नहीं है। +- इंस्टेंस का प्रबंधन किए बिना `fireworks()` को लूप में कॉल करना — प्रभाव पहले से ही निरंतर है। +- पेज छोड़ते समय इंस्टेंस को न रोकना — `instance?.pause()` या `instance?.stop()` कॉल करें। -## Related pages +## यह भी देखें -- Overview: [`/guide/bundles`](/hi/guide/bundles) -- Playground bundles: [`/playground/bundles`](/hi/playground/bundles) +- [बंडल अवलोकन](/hi/guide/bundles) +- [कॉनफ़ेटी बंडल](/hi/guide/bundles-confetti) diff --git a/websites/website/docs/hi/guide/bundles-full.md b/websites/website/docs/hi/guide/bundles-full.md index a122c830918..43394cc711c 100644 --- a/websites/website/docs/hi/guide/bundles-full.md +++ b/websites/website/docs/hi/guide/bundles-full.md @@ -1,21 +1,48 @@ # Bundle: tsparticles (Full) -`tsparticles` full bundle है, जो एक loader के साथ official features का बड़ा सेट देता है। +`tsparticles` (npm: `tsparticles`, लोडर: `loadFull`) आधिकारिक फुल बंडल है। इसमें Slim से सब कुछ प्लस एमिटर, एब्ज़ॉर्बर, टेक्स्ट शेप और उन्नत एनिमेशन (वॉबल, रोल, टिल्ट, ट्विंकल, डिस्ट्रॉय) शामिल हैं। -## tsparticles (Full) कब चुनें +## शामिल सुविधाएँ -- आपको कई official features चाहिए, बिना plugins manually चुनने के। -- आप fine-tuning से पहले production-ready complete base चाहते हैं। -- आप `tsParticles` API से engine को direct control करना चाहते हैं। +`@tsparticles/slim` से सब कुछ इनहेरिट करता है, साथ ही: + +**अतिरिक्त शेप:** text (कस्टम फ़ॉन्ट के साथ) + +**अतिरिक्त बाहरी इंटरैक्शन:** + +- drag (कणों को माउस से खींचें) +- trail (माउस के पीछे कण ट्रेल) + +**अतिरिक्त अपडेटर:** + +- destroy (कण विनाश एनिमेशन) +- roll (रोलिंग) +- tilt (3D झुकाव) +- twinkle (आंतरायिक चमक) +- wobble (दोलन) + +**प्लगइन:** + +- absorbers (ब्लैक होल जो कणों को सोख लेते हैं) +- emitters (निरंतर कण स्रोत) +- emitters-shape-circle, emitters-shape-square (एमिटर शेप) + +## कब उपयोग करें + +- एमिटर (लगातार कण उत्पन्न करना) की आवश्यकता +- एब्ज़ॉर्बर (कणों को सोखना) की आवश्यकता +- कस्टम फ़ॉन्ट के साथ टेक्स्ट शेप की आवश्यकता +- उन्नत एनिमेशन (वॉबल, टिल्ट, रोल, ट्विंकल) की आवश्यकता +- व्यक्तिगत प्लगइन पर जाने से पहले अच्छा कदम ## इंस्टॉलेशन +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine tsparticles ``` -## Setup उदाहरण - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadFull } from "tsparticles"; @@ -25,20 +52,65 @@ await loadFull(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { - number: { value: 100 }, - move: { enable: true, speed: 2 }, + number: { value: 50 }, + shape: { type: "text", options: { text: ["🔥", "✨", "⭐"] } }, + size: { value: 24 }, + move: { enable: true, speed: 1 }, + wobble: { enable: true, distance: 10 }, + }, + emitters: { + direction: "top", + rate: { quantity: 2, delay: 0.3 }, }, }, }); ``` -## Common pitfalls +### CDN (script टैग) + +```html + + + +``` + +## `tsparticles` और `@tsparticles/all` के बीच अंतर + +| पहलू | `tsparticles` (full) | `@tsparticles/all` | +| --------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| आकार | मध्यम | बहुत बड़ा | +| शेप | circle, square, star, polygon, line, image, emoji, text | सभी शेप (heart, cards, arrow, spiral, cog, rounded-rect, आदि) | +| इंटरैक्शन | Slim + drag + trail | सभी (cannon, light, pop, particle, repulse) | +| पथ | केवल Quad easing | 14 पथ जनरेटर | +| इफ़ेक्ट | कोई नहीं | 5 इफ़ेक्ट (bubble, filter, shadow, आदि) | +| एक्सपोर्ट | कोई नहीं | Image, JSON, Video | +| अतिरिक्त प्लगइन | absorbers, emitters | सभी (sounds, themes, trail, zoom, polygon-mask, canvas-mask, background-mask, आदि) | +| ईज़िंग | Quad | 15 ईज़िंग | + +## सामान्य गलतियाँ -- `loadFull(...)` से पहले `tsParticles.load(...)` कॉल करना। -- यह मान लेना कि यह `@tsparticles/all` जैसा ही पैकेज है (दोनों अलग bundles हैं)। +- `tsparticles` को `@tsparticles/all` समझने की भूल — ये अलग पैकेज हैं। +- `loadFull(tsParticles)` से पहले `tsParticles.load()` कॉल करना। +- npm पैकेज `tsparticles` है (`@tsparticles/full` नहीं), लोडर `loadFull` है। -## संबंधित पेज +## यह भी देखें -- ओवरव्यू: [`/guide/bundles`](/hi/guide/bundles) -- इंस्टॉलेशन मैट्रिक्स: [`/guide/installation`](/hi/guide/installation) +- [बंडल अवलोकन](/hi/guide/bundles) +- [इंस्टॉलेशन गाइड](/hi/guide/installation) diff --git a/websites/website/docs/hi/guide/bundles-particles.md b/websites/website/docs/hi/guide/bundles-particles.md index 8841c3bade8..81fcad5477f 100644 --- a/websites/website/docs/hi/guide/bundles-particles.md +++ b/websites/website/docs/hi/guide/bundles-particles.md @@ -1,42 +1,98 @@ # Bundle: Particles -`@tsparticles/particles` simple particles backgrounds के लिए focused API देता है। +`@tsparticles/particles` इंटरैक्टिव कण पृष्ठभूमि बनाने के लिए एक सरलीकृत API प्रदान करता है। `@tsparticles/basic` का एक समृद्ध विकल्प जिसमें मैन्युअल इंजन कॉन्फ़िगरेशन के बजाय समर्पित API है। -## Particles कब चुनें +## शामिल सुविधाएँ -- आपको particles background के लिए quick API चाहिए। -- आप engine/plugins manually wire नहीं करना चाहते। -- आप compact app-like API पसंद करते हैं। +**शेप:** circle (basic से) + +**आंतरिक प्लगइन:** interactivity (links, collisions) + +**इंटरैक्शन:** links (कण कनेक्शन), collisions + +**API:** `particles(options)` या `particles(canvasId, options)` + +## कब उपयोग करें + +- वेबसाइट के लिए कण पृष्ठभूमि +- कण लिंक के साथ पृष्ठभूमि (नोड-शैली प्रभाव) +- आप मैन्युअल रूप से इंजन कॉन्फ़िगर नहीं करना चाहते ## इंस्टॉलेशन +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/particles ``` -## Setup example - ```ts import { particles } from "@tsparticles/particles"; +// लिंक के साथ पृष्ठभूमि await particles({ count: 120, links: true, - linksColor: "#0ff", + color: "#ffffff", + linksColor: "#00d8ff", + radius: 3, + speed: 2, + opacity: 0.8, }); -await particles("canvas-id", { +// किसी विशिष्ट कैनवास पर +await particles("my-canvas", { count: 80, shape: ["circle", "square"], + links: true, }); + +// कस्टम रंगों के साथ +await particles({ + count: 100, + color: ["#ff6b6b", "#4ecdc4", "#45b7d1"], + links: false, +}); +``` + +### CDN (script टैग) + +```html + + ``` -## Common pitfalls +### मुख्य पैरामीटर + +| पैरामीटर | टाइप | डिफ़ॉल्ट | विवरण | +| ------------ | ------------------ | ---------- | ----------------- | +| `count` | number | 50 | कणों की संख्या | +| `radius` | number | 3 | कण त्रिज्या | +| `speed` | number | 2 | गति | +| `opacity` | number | 0.8 | अपारदर्शिता (0-1) | +| `color` | string \| string[] | "#ffffff" | कण रंग | +| `links` | boolean | false | लिंक दिखाएँ | +| `linksColor` | string | "#ffffff" | लिंक रंग | +| `linksWidth` | number | 1 | लिंक मोटाई | +| `shape` | string[] | ["circle"] | कण शेप | + +## सामान्य गलतियाँ -- मान लेना कि `@tsparticles/particles` से `tsParticles` export होता है। -- एक ही canvas id को अनजाने में reuse करना। +- यह सोचना कि `@tsparticles/particles` से `tsParticles` एक्सपोर्ट होता है — ऐसा नहीं है। +- अनजाने में उसी कैनवास ID का पुन: उपयोग करना। +- उन्नत शेप (स्टार, पॉलीगॉन) की अपेक्षा — particles बंडल basic पर आधारित है और केवल सर्कल का उपयोग करता है। -## Related pages +## यह भी देखें -- Overview: [`/guide/bundles`](/hi/guide/bundles) -- Playground bundles: [`/playground/bundles`](/hi/playground/bundles) +- [बंडल अवलोकन](/hi/guide/bundles) +- [आरंभ करना](/hi/guide/getting-started) diff --git a/websites/website/docs/hi/guide/bundles-slim.md b/websites/website/docs/hi/guide/bundles-slim.md index 0a122fd436a..3fda3f5537f 100644 --- a/websites/website/docs/hi/guide/bundles-slim.md +++ b/websites/website/docs/hi/guide/bundles-slim.md @@ -1,21 +1,61 @@ # Bundle: Slim -`@tsparticles/slim` ज्यादातर प्रोजेक्ट्स के लिए recommended default है। +`@tsparticles/slim` अधिकांश प्रोजेक्ट्स के लिए अनुशंसित बंडल है। इसमें माउस इंटरैक्शन, कई शेप और कण लिंक के साथ आधुनिक कण एनिमेशन के लिए आवश्यक सब कुछ शामिल है। -## Slim कब चुनें +## शामिल सुविधाएँ -- आपको size और features का अच्छा balance चाहिए। -- आप `tsParticles` engine API सीधे इस्तेमाल करते हैं। -- आपको common shapes/interactions चाहिए, लेकिन सब कुछ लोड नहीं करना। +`@tsparticles/basic` से सब कुछ इनहेरिट करता है, साथ ही: + +**शेप:** circle, square, star, polygon, line, image, emoji + +**बाहरी इंटरैक्शन (माउस/टच):** + +- attract +- bounce +- bubble +- connect +- destroy +- grab +- parallax +- pause +- push +- remove +- repulse +- slow + +**कण इंटरैक्शन:** + +- attract +- collisions +- links (कण कनेक्शन) + +**अतिरिक्त अपडेटर:** + +- life (जीवनचक्र) +- rotate + +**प्लगइन:** + +- interactivity +- easing-quad +- HEX, HSL, RGB रंग प्लगइन + +## कब उपयोग करें + +- अधिकांश प्रोजेक्ट्स के लिए अनुशंसित शुरुआती बिंदु +- कई शेप (सर्कल, स्टार, पॉलीगॉन, इमेज) की आवश्यकता +- माउस इंटरैक्शन (क्लिक, होवर, बबल, रिपल्स) की आवश्यकता +- कण लिंक की आवश्यकता +- बंडल आकार और सुविधाओं के बीच अच्छा संतुलन ## इंस्टॉलेशन +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/slim ``` -## Setup example - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; @@ -25,21 +65,47 @@ await loadSlim(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#0b1020" }, particles: { number: { value: 80 }, + links: { enable: true, distance: 150 }, move: { enable: true, speed: 2 }, - links: { enable: true }, + shape: { type: ["circle", "star", "square"] }, }, }, }); ``` -## Common pitfalls +### CDN (script टैग) + +```html + + + +``` + +## सामान्य गलतियाँ -- `loadSlim(...)` से पहले `tsParticles.load(...)` कॉल करना। -- engine और plugins की अलग-अलग versions मिलाना। +- `loadSlim(tsParticles)` से पहले `tsParticles.load()` कॉल करना। +- इंजन और बंडल के बीच अलग-अलग संस्करण मिलाना — उन्हें संरेखित रखें। +- उच्च बंडलों (एमिटर, एब्ज़ॉर्बर, टेक्स्ट, वॉबल) की सुविधाओं की अपेक्षा — `tsparticles` (full) या व्यक्तिगत प्लगइन की आवश्यकता है। -## Related pages +## यह भी देखें -- Overview: [`/guide/bundles`](/hi/guide/bundles) -- Installation matrix: [`/guide/installation`](/hi/guide/installation) +- [बंडल अवलोकन](/hi/guide/bundles) +- [इंस्टॉलेशन गाइड](/hi/guide/installation) diff --git a/websites/website/docs/hi/guide/bundles.md b/websites/website/docs/hi/guide/bundles.md index 1c7ccef4bce..11abec79b5c 100644 --- a/websites/website/docs/hi/guide/bundles.md +++ b/websites/website/docs/hi/guide/bundles.md @@ -1,104 +1,184 @@ -# Bundles गाइड - -यह पेज आपको सही `tsParticles` bundle चुनने और उसे जल्दी setup करने में मदद करता है। - -## पैकेज तुलना - -| पैकेज | किसके लिए बेहतर | setup स्टाइल | -| ------------------------ | ---------------------------------------- | ---------------------------------------------- | -| `@tsparticles/basic` | बहुत हल्के सेटअप | `tsParticles` + `await loadBasic(tsParticles)` | -| `@tsparticles/slim` | ज्यादातर वेबसाइट/ऐप्स | `tsParticles` + `await loadSlim(tsParticles)` | -| `tsparticles` | official full फीचर सेट और engine control | `tsParticles` + `await loadFull(tsParticles)` | -| `@tsparticles/all` | सभी फीचर्स, तेज prototyping | `tsParticles` + `await loadAll(tsParticles)` | -| `@tsparticles/confetti` | one-call confetti effects | `await confetti(options)` | -| `@tsparticles/fireworks` | one-call fireworks effects | `await fireworks(options)` | -| `@tsparticles/particles` | सरल particles background API | `await particles(options)` | -| `@tsparticles/ribbons` | one-call ribbons effects | `await ribbons(options)` | - -## Bundle guides - -- Basic: [`/guide/bundles-basic`](/hi/guide/bundles-basic) -- Slim: [`/guide/bundles-slim`](/hi/guide/bundles-slim) -- tsparticles (Full): [`/guide/bundles-full`](/hi/guide/bundles-full) -- All: [`/guide/bundles-all`](/hi/guide/bundles-all) -- Confetti: [`/guide/bundles-confetti`](/hi/guide/bundles-confetti) -- Fireworks: [`/guide/bundles-fireworks`](/hi/guide/bundles-fireworks) -- Particles: [`/guide/bundles-particles`](/hi/guide/bundles-particles) -- Ribbons (demo + docs): [`/demos/recipes/ribbons`](/hi/demos/recipes/ribbons) · - -## इंस्टॉलेशन - -अपने use case के अनुसार पैकेज path इंस्टॉल करें। - -```bash -pnpm add @tsparticles/engine @tsparticles/basic -pnpm add @tsparticles/engine @tsparticles/slim -pnpm add @tsparticles/engine tsparticles -pnpm add @tsparticles/engine @tsparticles/all -pnpm add @tsparticles/confetti -pnpm add @tsparticles/fireworks -pnpm add @tsparticles/particles -pnpm add @tsparticles/ribbons +# बंडल गाइड + +tsParticles मॉड्यूलर है। `@tsparticles/engine` पैकेज में केवल कोर इंजन है; दृश्य प्रभाव प्राप्त करने के लिए आपको **शेप** (क्या बनाना है), **अपडेटर** (कैसे एनिमेट करना है), **इंटरैक्शन** (माउस/टच पर कैसे प्रतिक्रिया करना है), और **प्लगइन** (अतिरिक्त सुविधाएँ) पंजीकृत करनी होंगी। यह सब **बंडल** के माध्यम से होता है। + +## बंडल श्रेणियाँ + +| श्रेणी | बंडल | API | +| ----------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------ | +| इंजन + लोडर | `@tsparticles/basic`, `@tsparticles/slim`, `tsparticles`, `@tsparticles/all` | `tsParticles.load({ id, options })` | +| समर्पित API | `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles`, `@tsparticles/ribbons` | `confetti({...})`, `fireworks({...})`, आदि | + +## पूर्ण सुविधा तुलना + +चिह्न: ● = शामिल, ○ = शामिल नहीं + +| सुविधा | basic | slim | full (`tsparticles`) | all | +| --------------------------------------------------------------------------------------------------- | ----- | ---- | -------------------- | ------------- | +| **शेप** | | | | | +| Circle | ● | ● | ● | ● | +| Square | ○ | ● | ● | ● | +| Star | ○ | ● | ● | ● | +| Polygon | ○ | ● | ● | ● | +| Line | ○ | ● | ● | ● | +| Image | ○ | ● | ● | ● | +| Emoji | ○ | ● | ● | ● | +| Text | ○ | ○ | ● | ● | +| Cards (सूट) | ○ | ○ | ○ | ● | +| Heart | ○ | ○ | ○ | ● | +| Arrow | ○ | ○ | ○ | ● | +| Rounded rect | ○ | ○ | ○ | ● | +| Rounded polygon | ○ | ○ | ○ | ● | +| Spiral | ○ | ○ | ○ | ● | +| Squircle | ○ | ○ | ○ | ● | +| Cog | ○ | ○ | ○ | ● | +| Infinity | ○ | ○ | ○ | ● | +| Matrix | ○ | ○ | ○ | ● | +| Path | ○ | ○ | ○ | ● | +| Ribbon | ○ | ○ | ○ | ● | +| **बाहरी इंटरैक्शन (माउस/टच)** | | | | | +| Attract | ○ | ● | ● | ● | +| Bounce | ○ | ● | ● | ● | +| Bubble | ○ | ● | ● | ● | +| Connect | ○ | ● | ● | ● | +| Destroy | ○ | ● | ● | ● | +| Grab | ○ | ● | ● | ● | +| Parallax | ○ | ● | ● | ● | +| Pause | ○ | ● | ● | ● | +| Push | ○ | ● | ● | ● | +| Remove | ○ | ● | ● | ● | +| Repulse | ○ | ● | ● | ● | +| Slow | ○ | ● | ● | ● | +| Drag | ○ | ○ | ● | ● | +| Trail | ○ | ○ | ● | ● | +| Cannon | ○ | ○ | ○ | ● | +| Particle | ○ | ○ | ○ | ● | +| Pop | ○ | ○ | ○ | ● | +| Light | ○ | ○ | ○ | ● | +| **कण इंटरैक्शन** | | | | | +| Links | ○ | ● | ● | ● | +| Collisions | ○ | ● | ● | ● | +| Attract | ○ | ● | ● | ● | +| Repulse | ○ | ○ | ○ | ● | +| **अपडेटर (एनिमेशन)** | | | | | +| Opacity | ● | ● | ● | ● | +| Size | ● | ● | ● | ● | +| Out modes | ● | ● | ● | ● | +| Paint (रंग) | ● | ● | ● | ● | +| Rotate | ○ | ● | ● | ● | +| Life | ○ | ● | ● | ● | +| Destroy | ○ | ○ | ● | ● | +| Roll | ○ | ○ | ● | ● | +| Tilt | ○ | ○ | ● | ● | +| Twinkle | ○ | ○ | ● | ● | +| Wobble | ○ | ○ | ● | ● | +| Gradient | ○ | ○ | ○ | ● | +| Orbit | ○ | ○ | ○ | ● | +| **प्लगइन** | | | | | +| Move | ● | ● | ● | ● | +| Blend | ● | ● | ● | ● | +| Emitters | ○ | ○ | ● | ● | +| Absorbers | ○ | ○ | ● | ● | +| Sounds | ○ | ○ | ○ | ● | +| Motion (उपयोगकर्ता प्राथमिकताएँ) | ○ | ○ | ○ | ● | +| Themes | ○ | ○ | ○ | ● | +| Polygon mask | ○ | ○ | ○ | ● | +| Canvas mask | ○ | ○ | ○ | ● | +| Background mask | ○ | ○ | ○ | ● | +| Export (इमेज, JSON, वीडियो) | ○ | ○ | ○ | ● | +| Manual particles | ○ | ○ | ○ | ● | +| Responsive | ○ | ○ | ○ | ● | +| Trail | ○ | ○ | ○ | ● | +| Zoom | ○ | ○ | ○ | ● | +| Poisson disc | ○ | ○ | ○ | ● | +| **पथ** | | | | | +| कोई भी पथ | ○ | ○ | ○ | ● (14 जनरेटर) | +| **इफ़ेक्ट** | | | | | +| Bubble, Filter, Shadow, आदि | ○ | ○ | ○ | ● (5 इफ़ेक्ट) | +| **ईज़िंग** | | | | | +| Quad | ○ | ● | ● | ● | +| Back, Bounce, Circ, Cubic, Elastic, Expo, Gaussian, Linear, Quart, Quint, Sigmoid, Sine, Smoothstep | ○ | ○ | ○ | ● | +| **रंग प्लगइन** | | | | | +| HEX, HSL, RGB | ● | ● | ● | ● | +| HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH | ○ | ○ | ○ | ● | + +### समर्पित API बंडल + +| सुविधा | confetti | fireworks | particles | ribbons | +| ------------ | --------------------------------------------------------- | ----------------------- | ------------------ | ---------------- | +| शेप | circle, heart, cards, emoji, image, polygon, square, star | line | (basic से) | ribbon | +| इंटरैक्शन | — | — | links + collisions | — | +| विशेष प्लगइन | emitters, motion | emitters, sounds, blend | — | emitters, motion | +| API कॉल | `confetti(opts)` | `fireworks(opts)` | `particles(opts)` | `ribbons(opts)` | + +## चयन गाइड + +```mermaid +flowchart TD + A[जल्दी शुरू करना चाहते हैं?] -->|हाँ| B[प्रीसेट का उपयोग करें?] + A -->|नहीं| C[कौन सा बंडल आकार?] + B -->|हाँ| D["@tsparticles/configs + @tsparticles/slim"] + B -->|नहीं| E["कॉनफ़ेटी? → @tsparticles/confetti"] + B -->|नहीं| F["आतिशबाज़ी? → @tsparticles/fireworks"] + B -->|नहीं| G["कण पृष्ठभूमि? → @tsparticles/particles"] + B -->|नहीं| H["रिबन? → @tsparticles/ribbons"] + C -->|"न्यूनतम (केवल सर्कल)"| I["@tsparticles/basic"] + C -->|"मध्यम (शेप + इंटरैक्शन)"| J["@tsparticles/slim"] + C -->|"अधिकतम (सभी सुविधाएँ)"| K["tsparticles (loadFull)"] + C -->|"पूरी रिपॉजिटरी"| L["@tsparticles/all"] ``` -CDN links और दूसरे package-manager variants चाहिए? - -- देखें [`/guide/installation`](/hi/guide/installation)। - -## Setup उदाहरण - -### Engine + loader bundles (`basic`, `slim`, `full`, `all`) - -```ts -import { tsParticles } from "@tsparticles/engine"; -import { loadSlim } from "@tsparticles/slim"; - -await loadSlim(tsParticles); - -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - number: { value: 80 }, - move: { enable: true, speed: 2 }, - }, - }, -}); +**सामान्य नियम:** + +1. अधिकांश प्रोजेक्ट `@tsparticles/slim` से शुरू करें। +2. यदि बंडल आकार महत्वपूर्ण है और आपको केवल सर्कल चाहिए: `@tsparticles/basic`। +3. यदि आपको एमिटर, एब्ज़ॉर्बर, टेक्स्ट, वॉबल/टिल्ट/रोल चाहिए: `tsparticles` `loadFull` के साथ। +4. सभी सुविधाओं के साथ त्वरित प्रोटोटाइप के लिए: `@tsparticles/all`। +5. न्यूनतम सेटअप के साथ लक्षित प्रभावों (कॉनफ़ेटी, आतिशबाज़ी, कण पृष्ठभूमि, रिबन) के लिए: समर्पित API बंडल। + +## त्वरित इंस्टॉल + +| बंडल | npm कमांड | लोडर फ़ंक्शन | CDN URL | +| ------------------------ | ------------------------------------------------- | ------------------------ | -------------------------------------------------------------- | +| `@tsparticles/basic` | `pnpm add @tsparticles/engine @tsparticles/basic` | `loadBasic(tsParticles)` | `@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| `@tsparticles/slim` | `pnpm add @tsparticles/engine @tsparticles/slim` | `loadSlim(tsParticles)` | `@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| `tsparticles` (full) | `pnpm add @tsparticles/engine tsparticles` | `loadFull(tsParticles)` | `tsparticles@4/tsparticles.bundle.min.js` | +| `@tsparticles/all` | `pnpm add @tsparticles/engine @tsparticles/all` | `loadAll(tsParticles)` | `@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| `@tsparticles/confetti` | `pnpm add @tsparticles/confetti` | `confetti(opts)` | `@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| `@tsparticles/fireworks` | `pnpm add @tsparticles/fireworks` | `fireworks(opts)` | `@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| `@tsparticles/particles` | `pnpm add @tsparticles/particles` | `particles(opts)` | `@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| `@tsparticles/ribbons` | `pnpm add @tsparticles/ribbons` | `ribbons(opts)` | `@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | + +**नोट:** basic/slim/full/all बंडल के लिए आपको `tsParticles.load()` से पहले `load*` कॉल करना होगा। CDN फ़ाइलें लोडर फ़ंक्शन को ग्लोबली एक्सपोज़ करती हैं लेकिन इसे ऑटो-कॉल नहीं करतीं। confetti/fireworks/particles/ribbons बंडल में स्व-निहित API है — सीधे `confetti()`, `fireworks()`, आदि कॉल करें। + +`@tsparticles/slim` के लिए CDN उदाहरण: + +```html + + + ``` -बाकी presets के लिए सिर्फ loader import/function बदलें: +`@tsparticles/confetti` के लिए CDN उदाहरण: -- `@tsparticles/basic` -> `loadBasic` -- `tsparticles` -> `loadFull` -- `@tsparticles/all` -> `loadAll` - -### Focused APIs (`confetti`, `fireworks`, `particles`, `ribbons`) - -```ts -import { confetti } from "@tsparticles/confetti"; -import { fireworks } from "@tsparticles/fireworks"; -import { particles } from "@tsparticles/particles"; -import { ribbons } from "@tsparticles/ribbons"; - -await confetti({ count: 80, spread: 60 }); -await fireworks({ sounds: false }); -await particles({ count: 100, links: true }); -await ribbons({ count: 5, spread: 0 }); +```html + + ``` -ये APIs तब शानदार हैं जब आप बहुत सारे engine plugins manually wire किए बिना जल्दी integration चाहते हैं। - -## व्यावहारिक चयन नियम - -1. ज्यादातर प्रोजेक्ट्स में `@tsparticles/slim` से शुरू करें। -2. अगर bundle size आपकी top priority है और features सरल हैं, तो `@tsparticles/basic` चुनें। -3. full baseline और `loadFull` चाहिए हो तो `tsparticles` चुनें। -4. prototyping के लिए या तुरंत ज्यादा features चाहिए हों तो `@tsparticles/all` चुनें। -5. UI में focused effect और minimal setup चाहिए हो तो `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles` या `@tsparticles/ribbons` चुनें। +इंस्टॉलेशन गाइड भी देखें: [`/hi/guide/installation`](/hi/guide/installation)। ## संबंधित पेज -- Playground focused bundles: [`/playground/bundles`](/hi/playground/bundles) -- Getting started path: [`/guide/getting-started`](/hi/guide/getting-started) -- Installation matrix: [`/guide/installation`](/hi/guide/installation) -- Wrappers overview: [`/guide/wrappers`](/hi/guide/wrappers) +- [आरंभ करना](/hi/guide/getting-started) +- [इंस्टॉलेशन गाइड](/hi/guide/installation) +- [प्रीसेट कैटलॉग](/hi/demos/presets) +- [पैलेट कैटलॉग](/hi/demos/palettes) +- [शेप कैटलॉग](/hi/demos/shapes) diff --git a/websites/website/docs/hi/guide/color-formats.md b/websites/website/docs/hi/guide/color-formats.md index a49ede85e69..64a06ff0fbe 100644 --- a/websites/website/docs/hi/guide/color-formats.md +++ b/websites/website/docs/hi/guide/color-formats.md @@ -1,6 +1,6 @@ # रंग प्रारूप -tsParticles `background`, `particles.color` और प्लगइन सेटिंग्स जैसे विकल्पों में कई रंग प्रारूप स्वीकार करता है। +tsParticles `background`, `particles.paint` और प्लगइन सेटिंग्स जैसे विकल्पों में कई रंग प्रारूप स्वीकार करता है। ## सामान्य प्रारूप diff --git a/websites/website/docs/hi/guide/getting-started.md b/websites/website/docs/hi/guide/getting-started.md index 6f68eb52a44..1ce27e9d2d2 100644 --- a/websites/website/docs/hi/guide/getting-started.md +++ b/websites/website/docs/hi/guide/getting-started.md @@ -1,106 +1,197 @@ # आरंभ करना -यह पथ 2026 में `tsParticles` के लिए सबसे तेज़ विश्वसनीय सेटअप है। +tsParticles एक JavaScript/TypeScript लाइब्रेरी है जो कण एनिमेशन, कॉनफ़ेटी, आतिशबाज़ी और बहुत कुछ बनाने के लिए है। यह किसी भी आधुनिक ब्राउज़र में काम करता है और npm पैकेज और CDN दोनों के रूप में ` + + + + +
+ + + +``` + +> **नोट**: CDN बंडल के साथ भी आपको `tsParticles.load()` से पहले `loadSlim(tsParticles)` (या `loadBasic` / `loadFull` / `loadAll`) कॉल करना होगा। CDN बंडल लोडर फ़ंक्शन को ग्लोबली एक्सपोज़ करते हैं लेकिन इसे ऑटो-कॉल नहीं करते। + +यही पैटर्न `@tsparticles/basic` → `loadBasic`, `tsparticles` → `loadFull`, `@tsparticles/all` → `loadAll` पर लागू होता है। + +### पथ C — समर्पित API वाले विशेष बंडल (confetti, fireworks, particles) + +कुछ बंडलों का अपना सरलीकृत API होता है, `tsParticles.load()` का उपयोग करने की आवश्यकता नहीं: + +```html + + + + + + + + + +``` + +यही `fireworks()`, `particles()`, `ribbons()` के लिए भी है। -- `@tsparticles/slim`: अधिकांश ऐप्स को यहां प्रारंभ करना चाहिए। -- `@tsparticles/basic`: बहुत हल्के सेटअप के लिए छोटा फीचर सेट। -- `@tsparticles/all`: सब कुछ शामिल है, तेज़ प्रोटोटाइप के लिए सबसे आसान। +## कौन सा बंडल चुनें? -यदि आपको सीधे `tsParticles` सेटअप के बजाय एक केंद्रित API की आवश्यकता है: +| बंडल | npm | कब उपयोग करें | +| ------------------------ | ------------------------ | --------------------------------------------------------------------------------------------------------- | +| `@tsparticles/basic` | `loadBasic(tsParticles)` | न्यूनतम: सर्कल, मूवमेंट, ओपेसिटी, साइज़। कोई इंटरैक्शन नहीं। | +| `@tsparticles/slim` | `loadSlim(tsParticles)` | **अधिकांश प्रोजेक्ट्स के लिए अनुशंसित।** इंटरैक्शन (क्लिक/होवर), कण लिंक, इमेज, स्टार, पॉलीगॉन जोड़ता है। | +| `tsparticles` | `loadFull(tsParticles)` | पूर्ण आधिकारिक फीचर सेट: एमिटर, एब्ज़ॉर्बर, टेक्स्ट शेप, रोल, वॉबल, ट्रेल। | +| `@tsparticles/all` | `loadAll(tsParticles)` | रिपॉजिटरी में **सब कुछ**: हर शेप, इंटरैक्शन, इफ़ेक्ट, ईज़िंग, पथ, एक्सपोर्ट। केवल प्रोटोटाइप के लिए। | +| `@tsparticles/confetti` | `confetti(options)` | एक फ़ंक्शन कॉल में कॉनफ़ेटी। समर्पित API। | +| `@tsparticles/fireworks` | `fireworks(options)` | एक फ़ंक्शन कॉल में आतिशबाज़ी। समर्पित API। | +| `@tsparticles/particles` | `particles(options)` | सरलीकृत कण पृष्ठभूमि। समर्पित API। | +| `@tsparticles/ribbons` | `ribbons(options)` | रिबन प्रभाव। समर्पित API। | -- `@tsparticles/particles`: सरलीकृत कण पृष्ठभूमि एपीआई -- `@tsparticles/confetti`: एक call में confetti API -- `@tsparticles/fireworks`: एक call में fireworks API +अधिक जानकारी: [`/hi/guide/bundles`](/hi/guide/bundles)। -## 5) जब आपको गति की आवश्यकता हो तो प्रीसेट/कॉन्फ़िगरेशन का उपयोग करें +## प्रीसेट का उपयोग करना -यदि आप पूर्वनिर्मित प्रभाव पसंद करते हैं: +`@tsparticles/configs` पैकेज में दर्जनों तैयार कॉन्फ़िगरेशन हैं (एब्ज़ॉर्बर, बबल, स्नो, स्टार, ग्रैविटी, कोलिज़न, आदि)। ```bash -pnpm add @tsparticles/configs +pnpm add @tsparticles/engine @tsparticles/slim @tsparticles/configs +``` + +```ts +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import "@tsparticles/configs"; + +await loadSlim(tsParticles); + +await tsParticles.load({ + id: "tsparticles", + options: { preset: "snow" }, +}); ``` -फिर कुंजी द्वारा एक कॉन्फ़िगरेशन लोड करें, जैसे [`demo/vite` ऐप](https://github.com/tsparticles/tsparticles/blob/main/demo/vite/src/main.ts)। +CDN के साथ: -यदि आप प्रीसेट-नाम आधारित सेटअप पसंद करते हैं, तो [`/demos/presets`](/hi/demos/presets) में आधिकारिक प्रीसेट कैटलॉग का उपयोग करें। +```html + + + + +``` -## त्वरित दस्तावेज़ीकरण मानचित्र +## त्वरित संदर्भ -- रूट विकल्प: [`/options/`](/hi/options/) -- रैपर संदर्भ: [`/guide/wrappers`](/hi/guide/wrappers) -- प्रीसेट कैटलॉग: [`/demos/presets`](/hi/demos/presets) -- पैलेट कैटलॉग: [`/demos/palettes`](/hi/demos/palettes) -- शेप कैटलॉग: [`/demos/shapes`](/hi/demos/shapes) -- particles.js से माइग्रेशन: [`/migrations/particles-js`](/hi/migrations/particles-js) -- रंग प्रारूप: [`/guide/color-formats`](/hi/guide/color-formats) -- कंटेनर जीवनचक्र: [`/guide/container-lifecycle`](/hi/guide/container-lifecycle) -- प्लगइन्स और अनुकूलन: [`/guide/plugins-customization`](/hi/guide/plugins-customization) +- ऑप्शन दस्तावेज़ीकरण: [`/hi/options/`](/hi/options/) +- बंडल गाइड: [`/hi/guide/bundles`](/hi/guide/bundles) +- प्रीसेट कैटलॉग: [`/hi/demos/presets`](/hi/demos/presets) +- पैलेट कैटलॉग: [`/hi/demos/palettes`](/hi/demos/palettes) +- शेप कैटलॉग: [`/hi/demos/shapes`](/hi/demos/shapes) +- फ्रेमवर्क रैपर: [`/hi/guide/wrappers`](/hi/guide/wrappers) +- रंग प्रारूप: [`/hi/guide/color-formats`](/hi/guide/color-formats) +- कंटेनर जीवनचक्र: [`/hi/guide/container-lifecycle`](/hi/guide/container-lifecycle) +- प्लगइन और अनुकूलन: [`/hi/guide/plugins-customization`](/hi/guide/plugins-customization) ## समस्या निवारण -- खाली स्क्रीन: `tsParticles.load` पर कॉल करने से पहले सत्यापित करें कि `#tsparticles` मौजूद है। -- अनुपलब्ध सुविधा: आपको संभवतः किसी अन्य प्लगइन/पैकेज (आकार, इंटरेक्शन, अपडेटर) की आवश्यकता होगी। -- विकल्पों पर त्रुटियाँ टाइप करें: अपने पैकेजों को उसी प्रमुख/लघु संस्करण के साथ संरेखित रखें। +| समस्या | संभावित कारण | समाधान | +| ------------------------------------------------------ | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| खाली स्क्रीन, कोई कण नहीं | `#tsparticles` DOM में मौजूद नहीं है जब `tsParticles.load()` कॉल किया गया | स्क्रिप्ट से पहले DIV मौजूद होना सुनिश्चित करें, या `DOMContentLoaded` का उपयोग करें | +| खाली स्क्रीन, कोई कण नहीं | केवल `@tsparticles/engine` इंस्टॉल किया | एक बंडल (`@tsparticles/slim`) या प्लगइन भी इंस्टॉल करें — इंजन अकेले कोई शेप नहीं बनाता | +| "loadBasic/loadSlim/loadFull is not a function" त्रुटि | बंडल इंस्टॉल नहीं या गलत import | `pnpm add @tsparticles/slim` और `{ loadSlim }` import करें | +| कण हिलते नहीं हैं | `move.enable` `true` पर सेट नहीं है | `move: { enable: true, speed: 2 }` जोड़ें | +| लापता सुविधा (जैसे लिंक, कोलिज़न) | चुने गए बंडल में वह शामिल नहीं है | एक समृद्ध बंडल (`@tsparticles/slim` या `tsparticles`) पर स्विच करें या विशिष्ट प्लगइन इंस्टॉल करें | +| TypeScript टाइप त्रुटियाँ | पैकेज संस्करण बेमेल हैं | इंजन और बंडल को एक ही मेजर/माइनर संस्करण पर रखें | diff --git a/websites/website/docs/hi/guide/installation.md b/websites/website/docs/hi/guide/installation.md index 1cf25a13f37..261b795e7bc 100644 --- a/websites/website/docs/hi/guide/installation.md +++ b/websites/website/docs/hi/guide/installation.md @@ -1,109 +1,146 @@ -# Installation +# इंस्टॉलेशन -यह पेज `tsParticles` के main README में दी गई installation matrix को फॉलो करता है। +## अपना रास्ता चुनें -Official reference: +| परिदृश्य | कमांड | +| ------------------------ | ------------------------------------------------- | +| त्वरित शुरुआत (अनुशंसित) | `pnpm add @tsparticles/engine @tsparticles/slim` | +| न्यूनतम सेटअप | `pnpm add @tsparticles/engine @tsparticles/basic` | +| पूर्ण फीचर सेट | `pnpm add @tsparticles/engine tsparticles` | +| रिपॉजिटरी में सब कुछ | `pnpm add @tsparticles/engine @tsparticles/all` | +| केवल कॉनफ़ेटी | `pnpm add @tsparticles/confetti` | +| केवल आतिशबाज़ी | `pnpm add @tsparticles/fireworks` | +| कण पृष्ठभूमि | `pnpm add @tsparticles/particles` | +| रिबन प्रभाव | `pnpm add @tsparticles/ribbons` | -## अपना path चुनें +> **महत्वपूर्ण**: `@tsparticles/engine` अकेला कुछ नहीं बनाता। आपको हमेशा एक बंडल (शेप और एनिमेशन लोड करने के लिए) या व्यक्तिगत प्लगइन जोड़ना होगा। बंडल गाइड देखें: [`/hi/guide/bundles`](/hi/guide/bundles)। -- **Fast default**: `@tsparticles/engine` + `@tsparticles/slim` -- **छोटा custom runtime**: `@tsparticles/engine` + केवल required plugins -- **Focused APIs**: `@tsparticles/particles`, `@tsparticles/confetti`, `@tsparticles/fireworks`, या `@tsparticles/ribbons` -- **All features included**: `@tsparticles/all` +## npm -## Hosting / CDN - -इन providers में से कोई भी उपयोग करें (या अपनी built files को self-host करें)। - -### jsDelivr - -- -- -- -- -- -- -- -- - -### cdnjs +```bash +# इंजन + स्लिम (अधिकांश प्रोजेक्ट्स के लिए अनुशंसित) +npm install @tsparticles/engine @tsparticles/slim -- +# इंजन + बेसिक (न्यूनतम) +npm install @tsparticles/engine @tsparticles/basic -### unpkg +# इंजन + फुल (tsparticles) +npm install @tsparticles/engine tsparticles -- -- -- -- -- -- -- -- +# इंजन + ऑल +npm install @tsparticles/engine @tsparticles/all -## Package manager से install करें +# समर्पित API बंडल (स्पष्ट इंजन की आवश्यकता नहीं) +npm install @tsparticles/confetti +npm install @tsparticles/fireworks +npm install @tsparticles/particles +npm install @tsparticles/ribbons +``` -### npm +## yarn ```bash -npm install @tsparticles/engine +yarn add @tsparticles/engine @tsparticles/slim +# ... अन्य बंडलों के लिए समान पैटर्न ``` -### yarn +## pnpm ```bash -yarn add @tsparticles/engine +pnpm add @tsparticles/engine @tsparticles/slim +# ... अन्य बंडलों के लिए समान पैटर्न ``` -### pnpm +## CDN (script टैग) -```bash -pnpm add @tsparticles/engine -``` +सभी पैकेज jsDelivr, unpkg और cdnjs पर उपलब्ध हैं। -## Import और require +### jsDelivr -```ts -const tsParticles = require("@tsparticles/engine"); +| बंडल | URL | +| --------------------- | ------------------------------------------------------------------------------------------- | +| इंजन | `https://cdn.jsdelivr.net/npm/@tsparticles/engine@4/tsparticles.engine.min.js` | +| Basic | `https://cdn.jsdelivr.net/npm/@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| Slim | `https://cdn.jsdelivr.net/npm/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| Full (`tsparticles`) | `https://cdn.jsdelivr.net/npm/tsparticles@4/tsparticles.bundle.min.js` | +| All | `https://cdn.jsdelivr.net/npm/@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| Confetti | `https://cdn.jsdelivr.net/npm/@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| Fireworks | `https://cdn.jsdelivr.net/npm/@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| Particles | `https://cdn.jsdelivr.net/npm/@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| Ribbons | `https://cdn.jsdelivr.net/npm/@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | +| particles.js अनुकूलता | `https://cdn.jsdelivr.net/npm/@tsparticles/pjs@4/tsparticles.pjs.min.js` | -// or +### unpkg -import { tsParticles } from "@tsparticles/engine"; -``` +समान संरचना: `https://unpkg.com/{package-name}@{version}/{filename}` + +उदाहरण: +`https://unpkg.com/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` + +### cdnjs -## Minimal runtime setup (`@tsparticles/slim`) +`https://cdnjs.com/libraries/tsparticles` + +## Import उदाहरण + +### बंडलर के साथ (ES module import) ```ts +// इंजन + बंडल लोडर import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; await loadSlim(tsParticles); +await tsParticles.load({ id: "tsparticles", options: { ... } }); +``` -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - move: { - enable: true, - }, - number: { - value: 60, - }, - }, - }, -}); +### CommonJS (require) के साथ + +```ts +const { tsParticles } = require("@tsparticles/engine"); +const { loadSlim } = require("@tsparticles/slim"); + +(async () => { + await loadSlim(tsParticles); + await tsParticles.load({ id: "tsparticles", options: { ... } }); +})(); ``` -## Related pages +### CDN (script टैग) के साथ + +```html + + + + + + +``` -- [`/guide/getting-started`](/hi/guide/getting-started) -- [`/guide/wrappers`](/hi/guide/wrappers) -- [`/demos/presets`](/hi/demos/presets) -- [`/migrations/particles-js`](/hi/migrations/particles-js) +समर्पित API बंडल के साथ: -## Legacy compatibility +```html + + +``` -अगर आप legacy particles.js integrations से migrate कर रहे हैं, तो compatibility package उपयोग करें: +## संबंधित पेज -- npm: -- jsDelivr: +- [आरंभ करना](/hi/guide/getting-started) +- [बंडल गाइड](/hi/guide/bundles) +- [फ्रेमवर्क रैपर](/hi/guide/wrappers) diff --git a/websites/website/docs/hi/guides/angular.md b/websites/website/docs/hi/guides/angular.md new file mode 100644 index 00000000000..89366c56812 --- /dev/null +++ b/websites/website/docs/hi/guides/angular.md @@ -0,0 +1,631 @@ +--- +title: एंगुलर इंटीग्रेशन +description: "@tsparticles/angular का उपयोग करके एंगुलर एप्लिकेशन में tsParticles को एकीकृत करने के लिए चरण-दर-चरण मार्गदर्शिका।" +--- + +# एंगुलर इंटीग्रेशन + +`@tsparticles/angular` पैकेज tsParticles के लिए एंगुलर कम्पोनेंट, मॉड्यूल और सेवाएँ प्रदान करता है। यह मार्गदर्शिका पारंपरिक `NgModule` दृष्टिकोण के साथ-साथ एंगुलर 17+ स्टैंडअलोन कम्पोनेंट को भी कवर करती है। + +--- + +## इंस्टॉलेशन + +```bash +npm install @tsparticles/angular @tsparticles/engine +``` + +पूर्ण सुविधा सेट के लिए, पूरा बंडल इंस्टॉल करें: + +```bash +npm install tsparticles +``` + +वैकल्पिक प्रीसेट पैकेज: + +```bash +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +``` + +--- + +## मूल उपयोग (NgModule) + +### 1. मॉड्यूल आयात करें + +```typescript +import { NgModule } from "@angular/core"; +import { BrowserModule } from "@angular/platform-browser"; +import { NgParticlesModule } from "@tsparticles/angular"; +import { AppComponent } from "./app.component"; + +@NgModule({ + declarations: [AppComponent], + imports: [BrowserModule, NgParticlesModule], + bootstrap: [AppComponent], +}) +export class AppModule {} +``` + +### 2. इंजन को आरंभ करें + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d47a1", + }, + fpsLimit: 120, + particles: { + number: { + value: 80, + }, + color: { + value: "#ffffff", + }, + shape: { + type: "circle", + }, + opacity: { + value: 0.5, + }, + size: { + value: { min: 1, max: 5 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("पार्टिकल्स कंटेनर लोड हुआ", container); + } +} +``` + +### 3. टेम्पलेट + +```html + +``` + +--- + +## इंजन आरंभीकरण विवरण + +`NgParticlesService.init()` विधि को ठीक एक बार कॉल किया जाना चाहिए, आमतौर पर `AppComponent.ngOnInit()` में। यह एक कॉलबैक प्राप्त करता है जहाँ आप अपने एप्लिकेशन को आवश्यक प्लगइन/प्रीसेट लोड करते हैं। + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesService } from "@tsparticles/angular"; +import type { Engine } from "@tsparticles/engine"; + +@Component({ ... }) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + // छोटे बंडलों के लिए केवल आवश्यक सुविधाएँ लोड करें + await loadBasic(engine); // मूल आकार + हलचल + await loadEmittersPlugin(engine); // एमिटर आकार + }); + } +} +``` + +`tsparticles` से उपलब्ध लोडर फ़ंक्शन: + +| फ़ंक्शन | विवरण | +| ------------------- | -------------------------------------------------------------- | +| `loadFull(engine)` | सभी सुविधाएँ (सबसे बड़ा बंडल) | +| `loadBasic(engine)` | मुख्य आकार (वृत्त, वर्ग, बहुभुज, आदि) | +| `loadSlim(engine)` | अधिकांश सुविधाएँ, शायद ही उपयोग किए जाने वाले प्लगइन को छोड़कर | +| `loadAll(engine)` | `loadFull` के लिए अप्रचलित उपनाम | + +--- + +## कॉन्फ़ेटी प्रभाव + +```bash +npm install @tsparticles/preset-confetti +``` + +```typescript +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// NgParticlesService.init कॉलबैक में: +await loadConfettiPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "confetti", + background: { + color: "transparent", + }, +}; +``` + +या सुविधाजनक `` कम्पोनेंट का उपयोग करें: + +```typescript +// app.module.ts +import { NgParticlesModule } from "@tsparticles/angular"; + +@NgModule({ + imports: [NgParticlesModule], +}) +export class AppModule {} +``` + +```html + +``` + +--- + +## आतिशबाज़ी प्रभाव + +```bash +npm install @tsparticles/preset-fireworks +``` + +```typescript +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; + +// NgParticlesService.init कॉलबैक में: +await loadFireworksPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "fireworks", + background: { + color: "#000000", + }, +}; +``` + +या `` कम्पोनेंट का उपयोग करें: + +```html + +``` + +> आतिशबाज़ी को स्वचालित रूप से शुरू करने से बचें; इसे किसी उपयोगकर्ता क्रिया (क्लिक, स्क्रॉल) से बाँधें ताकि अवांछित संसाधन उपयोग को रोका जा सके। + +--- + +## कस्टम पार्टिकल्स कॉन्फ़िगरेशन + +इंटरैक्टिविटी के साथ पूर्ण-सुविधायुक्त कस्टम पार्टिकल सेटअप: + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-particles", + templateUrl: "./particles.component.html", +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d0d0d", + }, + fpsLimit: 60, + particles: { + number: { + value: 100, + density: { + enable: true, + }, + }, + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + shape: { + type: ["circle", "square", "triangle"], + }, + opacity: { + value: 0.8, + random: true, + anim: { + enable: true, + speed: 1, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + random: true, + anim: { + enable: true, + speed: 4, + size_min: 1, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.3, + width: 1, + triangles: { + enable: true, + color: "#ffffff", + opacity: 0.05, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { + enable: true, + rotateX: 600, + rotateY: 600, + }, + }, + life: { + duration: { + value: 5, + random: true, + }, + count: 0, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: { + enable: true, + }, + }, + modes: { + grab: { + distance: 200, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + detectRetina: true, + }; + + particlesLoaded(container: Container): void { + console.log("कंटेनर लोड हुआ", container); + } +} +``` + +```html + +``` + +--- + +## इवेंट + +`ngx-particles` कम्पोनेंट `particlesLoaded` इवेंट उत्सर्जित करता है: + +```typescript +import type { Container } from "@tsparticles/engine"; + +// कम्पोनेंट विधि +onParticlesLoaded(container: Container): void { + // कंटेनर API तक पहुँच + container.pause(); + container.play(); + container.destroy(); + container.exportImage().then((blob) => { /* ... */ }); +} +``` + +```html + +``` + +कंटेनर संदर्भ आपको पूर्ण प्रोग्रामेटिक नियंत्रण देता है: रोकें, पुनरारंभ करें, नष्ट करें, निर्यात करें, और बहुत कुछ। + +--- + +## टेम्पलेट सिंटैक्स और सशर्त रेंडरिंग + +कम्पोनेंट को टॉगल करने के लिए एंगुलर स्ट्रक्चरल डायरेक्टिव का उपयोग करें: + +```html + + + +``` + +```typescript +export class AppComponent { + showParticles = true; + // ... +} +``` + +जब `*ngIf` `false` का मूल्यांकन करता है, तो कम्पोनेंट नष्ट हो जाता है (कैनवास और सभी पार्टिकल इंस्टेंस सहित)। इसे पुनः बनाने पर सब कुछ शुरू से आरंभ होता है। + +--- + +## स्टैंडअलोन कम्पोनेंट (एंगुलर 17+) + +एंगुलर 17+ में, आप `NgParticlesModule` को सीधे एक स्टैंडअलोन कम्पोनेंट में आयात कर सकते हैं: + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesModule, NgParticlesService } from "@tsparticles/angular"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +@Component({ + selector: "app-particles", + standalone: true, + imports: [NgParticlesModule], + template: ` + + `, +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 50 }, + color: { value: "#fff" }, + shape: { type: "circle" }, + move: { enable: true, speed: 2 }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("लोड हुआ", container); + } +} +``` + +किसी `NgModule` रैपर की आवश्यकता नहीं — बस कम्पोनेंट के `imports` एरे में `NgParticlesModule` आयात करें। + +--- + +## पूर्ण कम्पोनेंट उदाहरण + +### app.component.ts + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + title = "tsParticles एंगुलर डेमो"; + + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadSlim(engine); + }); + } + + particlesOptions: ISourceOptions = { + autoPlay: true, + background: { + color: "#1e1e2e", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMask: { + cover: { + color: "#1e1e2e", + }, + enable: false, + }, + fullScreen: { + enable: true, + zIndex: -1, + }, + detectRetina: true, + fpsLimit: 60, + particles: { + color: { + value: "#cdd6f4", + }, + links: { + color: "#cdd6f4", + distance: 150, + enable: true, + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1, + }, + number: { + value: 60, + }, + opacity: { + value: 0.6, + }, + size: { + value: { min: 1, max: 3 }, + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("पार्टिकल्स लोड हुए", container); + } +} +``` + +### app.component.html + +```html +
+ + +
+

{{ title }}

+

पार्टिकल्स पृष्ठभूमि में चल रहे हैं।

+
+
+``` + +### app.component.css + +```css +:host { + display: block; + width: 100%; + height: 100%; +} +``` + +--- + +## API संदर्भ + +| कम्पोनेंट | सिलेक्टर | विवरण | +| --------- | --------------- | ---------------------------------- | +| Particles | `ngx-particles` | पूर्ण पार्टिकल सिस्टम कम्पोनेंट | +| Confetti | `ngx-confetti` | पूर्व-कॉन्फ़िगर्ड कॉन्फ़ेटी प्रभाव | +| Fireworks | `ngx-fireworks` | पूर्व-कॉन्फ़िगर्ड आतिशबाज़ी प्रभाव | + +### `ngx-particles` इनपुट + +| इनपुट | प्रकार | डिफ़ॉल्ट | विवरण | +| --------- | ---------------- | --------------- | ------------------------ | +| `id` | `string` | `"tsparticles"` | कैनवास एलिमेंट आईडी | +| `options` | `ISourceOptions` | `{}` | पार्टिकल कॉन्फ़िगरेशन | +| `url` | `string` | — | दूरस्थ JSON कॉन्फ़िग URL | + +### `ngx-particles` आउटपुट + +| आउटपुट | पेलोड | विवरण | +| ----------------- | ----------- | ---------------------------------------------- | +| `particlesLoaded` | `Container` | जब कंटेनर आरंभ हो जाता है तब उत्सर्जित होता है | + +--- + +## समस्या निवारण + +- **खाली / अदृश्य कैनवास** — सुनिश्चित करें कि पैरेंट एलिमेंट की एक निश्चित ऊँचाई हो (जैसे, `height: 100vh`)। कैनवास कंटेनर के आयाम लेता है। +- **`NgParticlesService.init()` कई बार कॉल हुआ** — इसे केवल एक बार कॉल करें, आमतौर पर `AppComponent.ngOnInit()` में। बाद के कॉल सुरक्षित लेकिन अनावश्यक हैं। +- **मॉड्यूल नहीं मिला** — सत्यापित करें कि `@tsparticles/angular` `package.json` निर्भरताओं में सूचीबद्ध है और आपने `NgParticlesModule` आयात किया है। +- **`NullInjectorError: No provider for NgParticlesService`** — आपको उस मॉड्यूल में `NgParticlesModule` आयात (या पुनः निर्यात) करना होगा जहाँ आप कम्पोनेंट प्रदान करते हैं। diff --git a/websites/website/docs/hi/guides/astro.md b/websites/website/docs/hi/guides/astro.md new file mode 100644 index 00000000000..5615f3c0f8b --- /dev/null +++ b/websites/website/docs/hi/guides/astro.md @@ -0,0 +1,384 @@ +# एस्ट्रो इंटीग्रेशन + +अपनी एस्ट्रो साइट में आधिकारिक `@tsparticles/astro` इंटीग्रेशन पैकेज के साथ tsParticles का उपयोग करें। + +## इंस्टॉलेशन + +एस्ट्रो इंटीग्रेशन और tsParticles कोर को अपने पैकेज मैनेजर के माध्यम से इंस्टॉल करें: + +```bash +npm install @tsparticles/astro tsparticles +``` + +```bash +pnpm add @tsparticles/astro tsparticles +``` + +```bash +yarn add @tsparticles/astro tsparticles +``` + +## इंजन आरंभीकरण + +tsParticles एक मॉड्यूलर आर्किटेक्चर का उपयोग करता है। पार्टिकल्स रेंडर करने से पहले, आपको आवश्यक सुविधाओं के साथ इंजन को आरंभ करना होगा। एक क्लाइंट स्क्रिप्ट बनाएँ (जैसे, `src/scripts/particles-init.ts`) या अपने एस्ट्रो कम्पोनेंट में इनलाइन ` +``` + +> `id` प्रॉप अंतर्निहित कैनवास कंटेनर `
` को पास किया जाता है। इसका उपयोग स्टाइलिंग या `document.getElementById()` के माध्यम से अनिवार्य पहुँच के लिए करें। + +## टाइपस्क्रिप्ट सपोर्ट + +इंटीग्रेशन पूर्ण टाइपस्क्रिप्ट घोषणाओं के साथ आता है। अपने कॉन्फ़िगरेशन को टाइप करने के लिए `@tsparticles/engine` से `ISourceOptions` का उपयोग करें: + +```typescript +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { + value: 50, + density: { enable: true }, + }, + opacity: { value: 0.5 }, + shape: { type: "circle" }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + repulse: { distance: 200 }, + }, + }, +}; +``` + +## कस्टम कॉन्फ़िगरेशन + +नीचे एक अधिक विस्तृत कॉन्फ़िगरेशन है जिसे आप किसी भी एस्ट्रो पेज में डाल सकते हैं: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + autoPlay: true, + background: { + color: "#0d47a1", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMode: { + enable: true, + zIndex: -1, + }, + fpsLimit: 120, + particles: { + color: { + value: "#ffffff", + animation: { + enable: true, + speed: 20, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + triangles: { + enable: true, + opacity: 0.1, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "out", + attract: { enable: false }, + }, + number: { + value: 80, + density: { + enable: true, + }, + }, + opacity: { + value: 0.5, + animation: { + enable: true, + speed: 1, + sync: false, + }, + }, + shape: { + type: "circle", + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 3, + sync: false, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: true, + }, + modes: { + grab: { + distance: 200, + links: { opacity: 0.5 }, + }, + push: { quantity: 4 }, + }, + }, + detectRetina: true, +}; +--- + + + + +``` + +## प्रीसेट का उपयोग + +मैन्युअल रूप से कॉन्फ़िगरेशन बनाने के बजाय, इंजन आरंभीकरण के दौरान एक प्रीसेट लोड करें और विकल्पों में इसका संदर्भ दें: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + preset: "stars", + background: { color: "#000000" }, +}; +--- + + + + +``` + +## अन्य फ्रेमवर्क के साथ एकीकरण + +क्योंकि एस्ट्रो React, Vue, Svelte और Solid जैसे UI फ्रेमवर्क का समर्थन करता है, आप `.astro` फ़ाइलों के भीतर फ्रेमवर्क-विशिष्ट tsParticles कम्पोनेंट का उपयोग कर सकते हैं: + +### एस्ट्रो में React + +```astro +--- +import Particles from "@tsparticles/react"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +### एस्ट्रो में Vue + +```astro +--- +import Particles from "@tsparticles/vue3"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +> `client:load` निर्देश एस्ट्रो को बताता है कि पेज लोड होने पर तुरंत कम्पोनेंट को हाइड्रेट करें। विलंबित लोडिंग के लिए `client:visible` का उपयोग करें। + +## पूर्ण पेज उदाहरण + +एक संपूर्ण एस्ट्रो पेज जिसमें पार्टिकल्स एनिमेटेड पृष्ठभूमि के रूप में कार्य कर रहे हैं: + +```astro +--- +import Layout from "../layouts/Layout.astro"; +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + number: { value: 100 }, + color: { value: "#ffffff" }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + size: { + value: { min: 1, max: 4 }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, +}; +--- + + +
+

स्वागत है

+

इस पेज पर tsParticles द्वारा संचालित पार्टिकल पृष्ठभूमि है।

+
+ +
+ + + + +``` + +## कम्पोनेंट प्रॉप्स + +| प्रॉप | प्रकार | डिफ़ॉल्ट | विवरण | +| -------------------- | ---------------- | ------------------------- | ---------------------------------------- | +| `id` | `string` | `"tsparticles"` | कंटेनर के लिए DOM एलिमेंट आईडी | +| `options` | `ISourceOptions` | `{}` | पूर्ण tsParticles कॉन्फ़िगरेशन ऑब्जेकट | +| `url` | `string` | — | दूरस्थ JSON URL से कॉन्फ़िगरेशन लोड करें | +| `particlesClassName` | `string` | `"tsparticles-canvas-el"` | कैनवास एलिमेंट के लिए CSS क्लास | +| `container` | `object` | — | पूर्व-मौजूद `Container` इंस्टेंस (उन्नत) | diff --git a/websites/website/docs/hi/guides/ember.md b/websites/website/docs/hi/guides/ember.md new file mode 100644 index 00000000000..9fe9db31e6b --- /dev/null +++ b/websites/website/docs/hi/guides/ember.md @@ -0,0 +1,346 @@ +--- +title: एम्बर गाइड +description: एम्बर.जेएस एप्लिकेशन के साथ tsParticles को एकीकृत करने के लिए पूर्ण मार्गदर्शिका। +--- + +# एम्बर गाइड + +## विषय सूची + +1. [इंस्टॉलेशन](#installation) +2. [इंजन आरंभीकरण](#engine-initialization) +3. [मूल उपयोग](#basic-usage) +4. [कस्टम कॉन्फ़िगरेशन](#custom-configuration) +5. [इवेंट हैंडलिंग](#event-handling) +6. [सशर्त रेंडरिंग](#conditional-rendering) +7. [टाइपस्क्रिप्ट उदाहरण](#typescript-example) + +--- + +## इंस्टॉलेशन + +एम्बर ऐडऑन और tsParticles इंजन को ember-cli के माध्यम से इंस्टॉल करें: + +```bash +ember install @tsparticles/ember +``` + +यह ऐडऑन और इसकी सह-निर्भरता `tsparticles` को इंस्टॉल करेगा। आप वैकल्पिक रूप से प्रीसेट पैकेज जोड़ सकते हैं: + +```bash +npm install @tsparticles/slim +``` + +--- + +## इंजन आरंभीकरण + +ऐडऑन एक `initParticlesEngine` उपयोगिता निर्यात करता है जिसे आप एप्लिकेशन स्तर पर एक बार कॉल करते हैं। यह एक एसिंक कॉलबैक प्राप्त करता है जहाँ आप अपने ऐप को आवश्यक सुविधाएँ, प्रीसेट या आकार लोड करते हैं। + +```typescript +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadFull } from "tsparticles"; + +// इसे एप्लिकेशन बूटस्ट्रैप के दौरान कॉल करें +if (typeof window !== "undefined") { + void initParticlesEngine(async (engine) => { + await loadFull(engine); + }); +} +``` + +इस कॉल के लिए सामान्य स्थान एप्लिकेशन रूट का `beforeModel` हुक, एक एप्लिकेशन कंट्रोलर का कंस्ट्रक्टर, या एक इंस्टेंस इनिशियलाइज़र है। इंजन सिंगलटन एक बार आरंभ होता है और आपके ऐप में सभी `` कम्पोनेंट के बीच साझा होता है। + +--- + +## मूल उपयोग + +इंजन आरंभ करने के बाद, किसी भी टेम्पलेट में `` कम्पोनेंट का उपयोग करें। अपना पार्टिकल कॉन्फ़िगरेशन `@options` आर्गुमेंट के माध्यम से पास करें। + +```hbs +{{! app/templates/application.hbs }} + + +``` + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, + }; +} +``` + +--- + +## कस्टम कॉन्फ़िगरेशन + +इंटरैक्टिविटी, एकाधिक आकार और उत्तरदायी घनत्व के साथ एक समृद्ध कॉन्फ़िगरेशन बनाएँ। + +```typescript +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class IndexController extends Controller { + options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, + }; +} +``` + +```hbs + +``` + +--- + +## इवेंट हैंडलिंग + +`` कम्पोनेंट एक `@particlesLoaded` एक्शन फायर करता है जब कंटेनर आरंभीकरण पूरा कर लेता है और पहला फ्रेम रेंडर हो जाता है। प्रोग्रामेटिक नियंत्रण के लिए `Container` इंस्टेंस तक पहुँचने के लिए इसका उपयोग करें। + +```typescript +import Controller from "@ember/controller"; +import { action } from "@ember/object"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + /* ... */ + }; + + @action + loadedCallback(container: Container) { + console.log("पार्टिकल्स लोड हुए", container.id); + + // प्रोग्रामेटिक नियंत्रण उदाहरण: + setTimeout(() => { + container.pause(); + console.log("पार्टिकल्स 5 सेकंड बाद रुक गए"); + }, 5000); + } +} +``` + +```hbs + +``` + +यदि आप एक अलग एक्शन परिभाषित नहीं करना चाहते तो आप टेम्पलेट हेल्पर के साथ इनलाइन कॉलबैक पैटर्न का भी उपयोग कर सकते हैं। + +--- + +## सशर्त रेंडरिंग + +`` कम्पोनेंट कब रेंडर होगा यह नियंत्रित करने के लिए एम्बर के `{{if}}` हेल्पर का उपयोग `@tracked` प्रॉपर्टी के साथ करें। यह तब उपयोगी होता है जब इंजन आरंभीकरण एसिंक होता है और आप इंजन तैयार होने से पहले कम्पोनेंट को रेंडर करने से बचना चाहते हैं। + +```typescript +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked engineReady = false; + + options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { enable: true, speed: 1, outModes: { default: "bounce" } }, + }, + background: { color: "#1a1a2e" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } +} +``` + +```hbs +{{#if this.engineReady}} + +{{else}} +

पार्टिकल्स लोड हो रहे हैं...

+{{/if}} +``` + +`@tracked` डेकोरेटर सुनिश्चित करता है कि प्रॉमिस हल होने पर टेम्पलेट स्वचालित रूप से पुनः रेंडर हो। + +--- + +## टाइपस्क्रिप्ट उदाहरण + +नीचे एक पूर्ण, टाइप किया गया एम्बर एप्लिकेशन कंट्रोलर है जो स्लिम प्रीसेट, इंटरैक्टिविटी और लाइफसाइकिल प्रबंधन के साथ पूर्ण एकीकरण पैटर्न प्रदर्शित करता है। + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked private engineReady = false; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } + + @action + private handleParticlesLoaded(container: Container): void { + this.container = container; + console.log("कंटेनर में पार्टिकल्स लोड हुए:", container.id); + } +} +``` + +```hbs +{{! app/templates/application.hbs }} + +{{#if this.engineReady}} +
+

tsParticles + एम्बर

+ +
+{{else}} +
+

पार्टिकल इंजन आरंभ हो रहा है...

+
+{{/if}} +``` + +--- + +आपके पास अब एम्बर.जेएस एप्लिकेशन में tsParticles को एकीकृत करने के लिए आवश्यक सब कुछ है। प्रत्येक उदाहरण आत्मनिर्भर है और आपके प्रोजेक्ट में कॉपी करने के लिए तैयार है। diff --git a/websites/website/docs/hi/guides/index.md b/websites/website/docs/hi/guides/index.md new file mode 100644 index 00000000000..f68a8583d68 --- /dev/null +++ b/websites/website/docs/hi/guides/index.md @@ -0,0 +1,58 @@ +--- +title: चरण-दर-चरण मार्गदर्शिकाएँ +description: अपने प्रोजेक्ट में tsParticles को एकीकृत करने के लिए फ्रेमवर्क-विशिष्ट मार्गदर्शिकाएँ देखें। +--- + +# चरण-दर-चरण मार्गदर्शिकाएँ + +tsParticles गाइड अनुभाग में आपका स्वागत है। चाहे आप एक स्थिर Vanilla JS साइट बना रहे हों, React या Vue में एक सिंगल-पेज ऐप, या Next.js या Nuxt के साथ एक फुल-स्टैक एप्लिकेशन, ये चरण-दर-चरण ट्यूटोरियल आपको इंस्टॉलेशन, मूल उपयोग, उन्नत कॉन्फ़िगरेशन और इंटरैक्टिव प्रभावों के बारे में बताएंगे। + +प्रत्येक गाइड आत्मनिर्भर है और इसमें कॉपी-पेस्ट करने योग्य कोड उदाहरण शामिल हैं ताकि आप जल्दी से शुरुआत कर सकें। + +## उपलब्ध गाइड + +| फ्रेमवर्क / रैपर | पैकेज | विवरण | +| --------------------------------- | ------------------------------------- | ------------------------------------------------ | +| [Vanilla JS](./vanilla) | `tsparticles` (CDN या npm) | `tsParticles.load()` के साथ प्रत्यक्ष DOM एकीकरण | +| [React](./react) | `@tsparticles/react` | हुक और कम्पोनेंट API के साथ आधिकारिक React रैपर | +| [Vue 3](./vue3) | `@tsparticles/vue3` | कम्पोजेबल के साथ आधिकारिक Vue 3 प्लगइन | +| [Angular](./angular) | `@tsparticles/angular` | आधिकारिक Angular कम्पोनेंट और मॉड्यूल | +| [Svelte](./svelte) | `@tsparticles/svelte` | आधिकारिक Svelte कम्पोनेंट | +| [Next.js](./nextjs) | `@tsparticles/react` (Next.js के साथ) | सर्वर-साइड रेंडरिंग और डायनामिक इम्पोर्ट | +| [Nuxt](./nuxt) | `@tsparticles/vue3` (Nuxt के साथ) | Nuxt प्लगइन के रूप में SSR-सुरक्षित एकीकरण | +| [Solid](./solid) | `@tsparticles/solid` | आधिकारिक SolidJS रैपर | +| [Preact](./preact) | `@tsparticles/preact` | Preact-संगत कम्पोनेंट | +| [Lit](./lit) | `@tsparticles/lit` | Lit वेब कम्पोनेंट रैपर | +| [Qwik](./qwik) | `@tsparticles/qwik` | Qwik-अनुकूलित एकीकरण | +| [jQuery](./jquery) | `@tsparticles/jquery` | लीगेसी प्रोजेक्ट के लिए jQuery प्लगइन | +| [Astro](./astro) | `@tsparticles/react` (या कोई रैपर) | क्लाइंट निर्देशों के साथ आइलैंड आर्किटेक्चर | +| [Web Components](./webcomponents) | `@tsparticles/webcomponents` | कस्टम एलिमेंट्स API एकीकरण | +| [Stencil](./stencil) | `@tsparticles/stencil` | Stencil कम्पोनेंट रैपर | +| [Ember](./ember) | `@tsparticles/ember` | एम्बर ऐडऑन एकीकरण | +| [Riot](./riot) | `@tsparticles/riot` | Riot.js रैपर | +| [Inferno](./inferno) | `@tsparticles/inferno` | Inferno-संगत कम्पोनेंट | +| [WordPress](./wordpress) | प्लगइन + `tsparticles` | ब्लॉक एडिटर / शॉर्टकोड एकीकरण | + +## अपनी गाइड चुनें + +- [Vanilla JS (सादा जावास्क्रिप्ट)](./vanilla) +- [React](./react) +- [Vue 3](./vue3) +- [Angular](./angular) +- [Svelte](./svelte) +- [Next.js](./nextjs) +- [Nuxt](./nuxt) +- [Solid](./solid) +- [Preact](./preact) +- [Lit](./lit) +- [Qwik](./qwik) +- [jQuery](./jquery) +- [Astro](./astro) +- [Web Components](./webcomponents) +- [Stencil](./stencil) +- [Ember](./ember) +- [Riot](./riot) +- [Inferno](./inferno) +- [WordPress](./wordpress) + +शुभ निर्माण! diff --git a/websites/website/docs/hi/guides/inferno.md b/websites/website/docs/hi/guides/inferno.md new file mode 100644 index 00000000000..88c46413747 --- /dev/null +++ b/websites/website/docs/hi/guides/inferno.md @@ -0,0 +1,373 @@ +--- +title: इन्फेर्नो गाइड +description: इन्फेर्नो एप्लिकेशन के साथ tsParticles को एकीकृत करने के लिए पूर्ण मार्गदर्शिका। +--- + +# इन्फेर्नो गाइड + +## विषय सूची + +1. [इंस्टॉलेशन](#installation) +2. [मूल उपयोग](#basic-usage) +3. [इंजन आरंभीकरण](#engine-initialization) +4. [कस्टम कॉन्फ़िगरेशन](#custom-configuration) +5. [प्रीसेट उपयोग](#preset-usage) +6. [कम्पोनेंट पैटर्न](#component-pattern) +7. [टाइपस्क्रिप्ट उदाहरण](#typescript-example) + +--- + +## इंस्टॉलेशन + +इन्फेर्नो रैपर और tsParticles इंजन को npm के माध्यम से इंस्टॉल करें: + +```bash +npm install @tsparticles/inferno tsparticles +``` + +वैकल्पिक रूप से छोटे बंडल के लिए स्लिम प्रीसेट इंस्टॉल करें: + +```bash +npm install @tsparticles/slim +``` + +--- + +## मूल उपयोग + +`@tsparticles/inferno` पैकेज दो आइटम निर्यात करता है: `ParticlesProvider` और `Particles`. अपने पार्टिकल कम्पोनेंट को `ParticlesProvider` से रैप करें जो इंजन सेटअप के लिए एक `init` कॉलबैक स्वीकार करता है, फिर पार्टिकल कैनवास रेंडर करने के लिए `` का उपयोग करें। + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import { loadSlim } from "@tsparticles/slim"; + +const options = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +function App() { + return ( + { + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +`ParticlesProvider` को हर `` कम्पोनेंट का पूर्वज होना चाहिए। यह इंजन को एक बार आरंभ करता है और इसे संदर्भ के माध्यम से सभी चिल्ड्रन को प्रदान करता है। + +--- + +## इंजन आरंभीकरण + +`ParticlesProvider` एक `init` प्रॉप स्वीकार करता है जो इंजन इंस्टेंस प्राप्त करता है। यह वह जगह है जहाँ आप अपने ऐप को आवश्यक सुविधाएँ, आकार, प्रीसेट या अपडेटर लोड करते हैं। + +```tsx +// हल्का — वृत्त पार्टिकल्स, मूल हलचल, लिंक + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); +}}> + +// पूर्ण सुविधा सेट — सभी आकार, इंटरैक्शन, प्रभाव + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); +}}> + +// प्रीसेट-विशिष्ट — कॉन्फ़ेटी, आतिशबाज़ी, बर्फ, तारे + { + const { loadConfettiPreset } = await import("@tsparticles/preset-confetti"); + await loadConfettiPreset(engine); +}}> +``` + +कॉलबैक के अंदर डायनामिक `import()` का उपयोग करने से कोड स्प्लिटिंग सक्षम होती है: प्रीसेट या सुविधा मॉड्यूल केवल तब लोड होते हैं जब पार्टिकल कम्पोनेंट माउंट होता है। + +--- + +## कस्टम कॉन्फ़िगरेशन + +नीचे इंटरैक्टिविटी, एकाधिक आकार प्रकार और एक गहरे ग्रेडिएंट पृष्ठभूमि के साथ एक पूर्ण-सुविधायुक्त कॉन्फ़िगरेशन है। + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, +}; + +function App() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +--- + +## प्रीसेट उपयोग + +`@tsparticles/configs` पैकेज पूर्व-निर्मित कॉन्फ़िगरेशन प्रदान करता है जिसे आप सीधे `options` प्रॉप में पास कर सकते हैं। उन्हें `ParticlesProvider` init कॉलबैक में संबंधित प्रीसेट लोडर के साथ जोड़ें। + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import configs from "@tsparticles/configs"; + +function App() { + return ( + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +आप `configs.confetti` को किसी भी उपलब्ध प्रीसेट से बदल सकते हैं: `configs.basic`, `configs.fireworks`, `configs.snow`, `configs.stars`, आदि। + +--- + +## कम्पोनेंट पैटर्न + +बड़े एप्लिकेशन के लिए, अपने पार्टिकल लॉजिक को `particlesLoaded` कॉलबैक के साथ एक समर्पित कम्पोनेंट में संरचित करें ताकि `Container` इंस्टेंस तक पहुँचा जा सके। + +```tsx +import { render, Component } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +class ParticlesBackground extends Component { + private container?: Container; + + handleParticlesLoaded(container?: Container) { + this.container = container; + console.log("पार्टिकल्स लोड हुए:", container?.id); + } + + render() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); + } +} + +function App() { + return ( +
+

tsParticles + इन्फेर्नो

+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +## टाइपस्क्रिप्ट उदाहरण + +यहाँ एक पूर्ण, टाइप किया गया इन्फेर्नो एप्लिकेशन है जिसमें एक उत्तरदायी पार्टिकल कॉन्फ़िगरेशन और पूर्ण-स्क्रीन पृष्ठभूमि है। + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const particlesOptions: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +function handleInit(engine: Engine): Promise { + return import("@tsparticles/slim").then(({ loadSlim }) => loadSlim(engine)); +} + +function handleParticlesLoaded(container?: Container): void { + console.log("tsParticles कंटेनर तैयार:", container?.id); +} + +function App() { + return ( + +
+

tsParticles + इन्फेर्नो

+

पूर्ण टाइपस्क्रिप्ट एकीकरण

+
+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +आपके पास अब इन्फेर्नो एप्लिकेशन में tsParticles को एकीकृत करने के लिए आवश्यक सब कुछ है। प्रत्येक उदाहरण आत्मनिर्भर है और आपके प्रोजेक्ट में कॉपी करने के लिए तैयार है। diff --git a/websites/website/docs/hi/guides/jquery.md b/websites/website/docs/hi/guides/jquery.md new file mode 100644 index 00000000000..0c76258be8d --- /dev/null +++ b/websites/website/docs/hi/guides/jquery.md @@ -0,0 +1,274 @@ +# jQuery इंटीग्रेशन + +अपने jQuery-आधारित प्रोजेक्ट में आधिकारिक jQuery प्लगइन रैपर के साथ tsParticles को एकीकृत करें। + +## इंस्टॉलेशन + +### CDN के माध्यम से + +jQuery, tsParticles और jQuery प्लगइन को स्क्रिप्ट टैग के माध्यम से शामिल करें: + +```html + + + +``` + +--- + +### npm + बिल्ड के माध्यम से + +आवश्यक पैकेज इंस्टॉल करें: + +```bash +npm install jquery @tsparticles/jquery tsparticles +``` + +अपने प्रोजेक्ट में आयात करें: + +```javascript +import $ from "jquery"; +import "@tsparticles/jquery"; +``` + +## इंजन आरंभीकरण + +पार्टिकल्स रेंडर होने से पहले, tsParticles इंजन को आवश्यक सुविधाओं के साथ आरंभ किया जाना चाहिए। यह `$.particles.init` के माध्यम से किया जाता है: + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); +})(); +``` + +> **यह क्यों आवश्यक है?** tsParticles एक मॉड्यूलर आर्किटेक्चर का उपयोग करता है। `loadFull` सभी अंतर्निहित आकार, इंटरैक्शन और अपडेटर पंजीकृत करता है। आप बंडल आकार कम करने के लिए छोटे बंडल (जैसे, `tsparticles-slim`) आयात कर सकते हैं। + +## मूल उपयोग + +एक बार इंजन आरंभ हो जाने और DOM तैयार हो जाने पर, एक कंटेनर एलिमेंट चुनें और `.particles().load()` कॉल करें: + +```javascript +$(document).ready(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); + + $("#tsparticles") + .particles() + .load({ + background: { + color: "#0d47a1", + }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + }, + }); +}); +``` + +कंटेनर एलिमेंट DOM में मौजूद होना चाहिए: + +```html +
+``` + +## कस्टम कॉन्फ़िगरेशन + +`.load()` विधि पूर्ण `ISourceOptions` ऑब्जेकट स्वीकार करती है। यहाँ एक व्यापक उदाहरण है: + +```javascript +$("#tsparticles") + .particles() + .load({ + background: { + color: "#000000", + }, + fpsLimit: 120, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + direction: "none", + enable: true, + outModes: "bounce", + speed: 4, + }, + number: { + density: { + enable: true, + }, + value: 60, + }, + opacity: { + value: 0.6, + }, + shape: { + type: ["circle", "square", "triangle"], + }, + size: { + value: { min: 2, max: 8 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + }, + interactivity: { + events: { + onClick: { + enable: true, + mode: "push", + }, + onHover: { + enable: true, + mode: "repulse", + }, + }, + modes: { + push: { + quantity: 4, + }, + repulse: { + distance: 200, + }, + }, + }, + }); +``` + +## प्रीसेट लोडिंग + +यदि आपने एक प्रीसेट पैकेज (जैसे `tsparticles-preset-stars`) इंस्टॉल किया है, तो इसे इंजन आरंभीकरण के दौरान लोड करें और कॉन्फ़िगरेशन में इसका संदर्भ दें: + +```bash +npm install tsparticles-preset-stars +``` + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadStarsPreset } = await import("tsparticles-preset-stars"); + await loadStarsPreset(engine); + }); + + $("#tsparticles") + .particles() + .load({ + preset: "stars", + background: { color: "#0d47a1" }, + }); +})(); +``` + +## इवेंट हैंडलिंग और कंटेनर नियंत्रण + +`.particles()` एक jQuery प्लगइन इंस्टेंस लौटाता है। अंतर्निहित tsParticles `Container` तक पहुँचने और `play()`, `pause()`, या `destroy()` जैसी विधियाँ कॉल करने के लिए: + +```javascript +const $container = $("#tsparticles"); + +// पार्टिकल्स लोड करें +$container.particles().load({ + /* options */ +}); + +// कुछ सेकंड बाद प्ले/पॉज़ करें +setTimeout(() => { + const container = $container.particles().getContainer(); + container?.pause(); +}, 5000); +``` + +## पूर्ण उदाहरण + +नीचे एक पूर्ण, आत्मनिर्भर HTML पेज है जो CDN के माध्यम से tsParticles लोड करता है और इंटरैक्टिव प्रभावों के साथ एक पार्टिकल दृश्य रेंडर करता है: + +```html + + + + + + tsParticles + jQuery + + + +
+ + + + + + + +``` + +## API संदर्भ + +| विधि | विवरण | +| ---------------------------------- | ------------------------------------------------------ | +| `$.particles.init(fn)` | लोडर कॉलबैक के साथ इंजन आरंभ करें | +| `$(el).particles()` | एलिमेंट पर पार्टिकल्स प्लगइन इंस्टेंस बनाएँ | +| `$(el).particles().load(opts)` | पार्टिकल कॉन्फ़िगरेशन लोड और प्रारंभ करें | +| `$(el).particles().destroy()` | पार्टिकल इंस्टेंस नष्ट करें और साफ़ करें | +| `$(el).particles().getContainer()` | अनिवार्य नियंत्रण के लिए अंतर्निहित `Container` लौटाएँ | diff --git a/websites/website/docs/hi/guides/lit.md b/websites/website/docs/hi/guides/lit.md new file mode 100644 index 00000000000..9b2449a3f38 --- /dev/null +++ b/websites/website/docs/hi/guides/lit.md @@ -0,0 +1,301 @@ +--- +title: लिट +description: आधिकारिक @tsparticles/lit वेब कम्पोनेंट रैपर के साथ tsParticles को लिट में एकीकृत करें। +--- + +# लिट इंटीग्रेशन + +`@tsparticles/lit` पैकेज एक `` कस्टम एलिमेंट प्रदान करता है जो लिट के साथ बनाया गया है, जिससे आप किसी भी लिट प्रोजेक्ट या सादे HTML पेज में tsParticles का घोषणात्मक रूप से उपयोग कर सकते हैं। + +## इंस्टॉलेशन + +```bash +npm install @tsparticles/lit tsparticles +``` + +पैकेज पूरी तरह से टाइप किया गया है और पार्टिकल विकल्पों को प्रतिक्रियाशील रूप से अपडेट करने के लिए लिट के रिएक्टिव कंट्रोलर पैटर्न शामिल करता है। + +## इंजन आरंभीकरण + +`` कम्पोनेंट को पंजीकृत करने या अपने एप्लिकेशन में आयात करने से पहले `initParticlesEngine` कॉल करें। यह ठीक एक बार होना चाहिए। + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadFull } from "tsparticles"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +अनुकूलित बंडल आकार के लिए, केवल अपने प्रोजेक्ट को आवश्यक सुविधाएँ आयात करें: + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadBasic } from "@tsparticles/basic"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +void initParticlesEngine(async (engine) => { + await loadBasic(engine); + await loadConfettiPreset(engine); +}); +``` + +## मूल उपयोग + +इंजन आरंभ होने के बाद, किसी भी लिट टेम्पलेट या HTML फ़ाइल में `` एलिमेंट का उपयोग करें: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private options = { + background: { + color: "#0d1117", + }, + particles: { + number: { value: 60 }, + color: { value: "#58a6ff" }, + links: { + enable: true, + color: "#58a6ff", + }, + move: { enable: true, speed: 2 }, + }, + }; + + render() { + return html` `; + } +} +``` + +`.options` सिंटैक्स (आगे डॉट के साथ) लिट की प्रॉपर्टी बाइंडिंग है, जो सुनिश्चित करता है कि ऑब्जेकट को विशेषता के रूप में क्रमबद्ध करने के बजाय संदर्भ द्वारा पास किया जाता है। + +## सादा HTML उपयोग + +एक बार `@tsparticles/lit` बंडल या लोड हो जाने पर, एलिमेंट सादे HTML में भी काम करता है: + +```html + + + + + + + + + +``` + +आप एक न्यूनतम विकल्प ऑब्जेकट को JSON विशेषता के रूप में पास कर सकते हैं: + +```html + +``` + +## कस्टम कॉन्फ़िगरेशन + +एक पूर्ण tsParticles कॉन्फ़िगरेशन को लिट प्रॉपर्टी के रूप में पास करें: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-particles") +class MyParticles extends LitElement { + @property({ type: Object }) + options: ISourceOptions = { + background: { + color: "#0d1117", + }, + fpsLimit: 120, + fullScreen: { + enable: true, + zIndex: -1, + }, + particles: { + color: { + value: ["#ff5733", "#33ff57", "#3357ff"], + }, + links: { + color: "#ffffff", + enable: true, + opacity: 0.3, + distance: 150, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + }, + number: { + value: 100, + density: { + enable: true, + }, + }, + opacity: { + value: 0.6, + animation: { + enable: true, + speed: 0.5, + minimumValue: 0.1, + }, + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 2, + minimumValue: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + }, + modes: { + grab: { + distance: 180, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + }; + + render() { + return html` `; + } +} +``` + +## इवेंट हैंडलिंग + +`` एलिमेंट द्वारा प्रेषित `particles-loaded` कस्टम इवेंट को सुनें: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import type { Container } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private handleParticlesLoaded(e: CustomEvent) { + const container = e.detail; + console.log("पार्टिकल्स लोड हुए:", container); + container?.refresh(); + } + + render() { + return html` `; + } +} +``` + +## टाइपस्क्रिप्ट उदाहरण + +`initParticlesEngine`, रिएक्टिव विकल्प और इवेंट हैंडलिंग के साथ एक पूर्ण टाइप किया गया लिट एलिमेंट: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import { initParticlesEngine } from "@tsparticles/lit"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import "@tsparticles/lit"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +@customElement("particles-background") +class ParticlesBackground extends LitElement { + @property({ type: Object }) + options: ISourceOptions = {}; + + @property({ type: Boolean, attribute: "fullscreen" }) + fullscreen = true; + + protected onParticlesLoaded(e: CustomEvent) { + console.log("कंटेनर तैयार:", e.detail.id); + } + + render() { + return html` + + + `; + } +} +``` + +## डायनामिक अपडेट + +क्योंकि `` लिट की रिएक्टिव प्रॉपर्टीज़ का उपयोग करता है, `options` प्रॉपर्टी बदलने से पार्टिकल्स स्वचालित रूप से अपडेट हो जाते हैं: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("dynamic-particles") +class DynamicParticles extends LitElement { + @state() + private theme: "light" | "dark" = "dark"; + + private get options(): ISourceOptions { + return this.theme === "dark" + ? { + background: { color: "#0d1117" }, + particles: { color: { value: "#58a6ff" } }, + } + : { + background: { color: "#ffffff" }, + particles: { color: { value: "#0969da" } }, + }; + } + + private toggleTheme() { + this.theme = this.theme === "dark" ? "light" : "dark"; + } + + render() { + return html` + + + `; + } +} +``` + +कम्पोनेंट `options` प्रॉपर्टी पर नज़र रखता है और जब भी यह बदलता है, आंतरिक रूप से `refresh()` कॉल करता है, रनटाइम पर पार्टिकल कॉन्फ़िगरेशन को सहजता से अपडेट करता है। diff --git a/websites/website/docs/hi/guides/nextjs.md b/websites/website/docs/hi/guides/nextjs.md new file mode 100644 index 00000000000..56b0473bf04 --- /dev/null +++ b/websites/website/docs/hi/guides/nextjs.md @@ -0,0 +1,492 @@ +--- +title: Next.js इंटीग्रेशन +description: App Router का उपयोग करके Next.js एप्लिकेशन में tsParticles को एकीकृत करने के लिए चरण-दर-चरण मार्गदर्शिका। +--- + +# Next.js इंटीग्रेशन + +यह मार्गदर्शिका **App Router** (Next.js 13+) का उपयोग करके Next.js प्रोजेक्ट में tsParticles को एकीकृत करने को कवर करती है। लीगेसी Pages Router के लिए, नीचे [लीगेसी Pages Router](#legacy-pages-router) अनुभाग देखें। + +## इंस्टॉलेशन + +`@tsparticles/react` रैपर और पूर्ण `tsparticles` इंजन (या छोटे बिल्ड के लिए स्लिम बंडल) इंस्टॉल करें: + +```bash +npm install @tsparticles/react tsparticles +``` + +यदि आप छोटा `@tsparticles/slim` बंडल पसंद करते हैं: + +```bash +npm install @tsparticles/react @tsparticles/slim +``` + +## मूल उपयोग (App Router) + +Next.js App Router कम्पोनेंट डिफ़ॉल्ट रूप से सर्वर-साइड होते हैं। चूँकि tsParticles को ब्राउज़र `canvas` API की आवश्यकता है, आपको कम्पोनेंट को `"use client"` निर्देश से चिह्नित करना होगा। + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesBackground() { + const particlesLoaded = useCallback((container?: Container) => { + console.log("पार्टिकल्स लोड हुए", container); + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }), + [], + ); + + return ; +} +``` + +इसे `components/particles-background.tsx` के रूप में बनाएँ और किसी भी पेज या लेआउट में आयात करें। क्योंकि फ़ाइल `"use client"` से शुरू होती है, यह क्लाइंट पर रेंडर होगी — ठीक वहीं जहाँ tsParticles को होना चाहिए। + +## थीम स्विचिंग + +वर्तमान थीम स्थिति से विकल्प प्राप्त करके tsParticles को Next.js थीम टॉगल के साथ जोड़ें: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useMemo, useState, useCallback } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ThemeAwareParticles() { + const [theme, setTheme] = useState<"light" | "dark">("dark"); + + const toggleTheme = useCallback(() => { + setTheme((t) => (t === "dark" ? "light" : "dark")); + }, []); + + const particlesLoaded = useCallback((_container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { + color: theme === "dark" ? "#000000" : "#ffffff", + }, + particles: { + color: { value: theme === "dark" ? "#ffffff" : "#000000" }, + number: { value: 100 }, + links: { + enable: true, + color: theme === "dark" ? "#ffffff" : "#000000", + }, + move: { enable: true }, + }, + }), + [theme], + ); + + return ( + <> + + + + ); +} +``` + +`options` ऑब्जेकट `useMemo` के माध्यम से हर बार `theme` बदलने पर पुनः बनाया जाता है, इसलिए कैनवास स्वचालित रूप से अपडेट होता है। + +## कॉन्फ़ेटी प्रभाव + +बटन क्लिक जैसी घटनाओं पर उत्सवपूर्ण कॉन्फ़ेटी ट्रिगर करने के लिए `@tsparticles/preset-confetti` का उपयोग करें: + +```bash +npm install @tsparticles/preset-confetti +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Container, ISourceOptions, Engine } from "@tsparticles/engine"; + +export default function ConfettiButton() { + const [active, setActive] = useState(false); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadConfettiPreset(engine); + }, []); + + const particlesLoaded = useCallback( + async (container?: Container) => { + if (active && container) { + await container.play(); + } + }, + [active], + ); + + const options: ISourceOptions = useMemo( + () => ({ + preset: "confetti", + fullScreen: { zIndex: 1000 }, + }), + [], + ); + + const handleCelebrate = useCallback(() => { + setActive(true); + setTimeout(() => setActive(false), 5000); + }, []); + + return ( + <> + {active && } + + + ); +} +``` + +`init` कॉलबैक पार्टिकल्स बनने से पहले कॉन्फ़ेटी प्रीसेट को इंजन में लोड करता है। + +## आतिशबाज़ी प्रभाव + +इसी तरह, आतिशबाज़ी प्रीसेट एक शानदार आतिशबाजी प्रदर्शन बनाता है: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; +import type { Container, Engine } from "@tsparticles/engine"; + +export default function FireworksBackground() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFireworksPreset(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options = useMemo( + () => ({ + preset: "fireworks" as const, + fullScreen: { zIndex: -1 }, + background: { + color: "#000", + }, + }), + [], + ); + + return ; +} +``` + +## कंटेनर रेफ के साथ पूर्ण टाइपस्क्रिप्ट उदाहरण + +एनीमेशन को प्रोग्रामेटिक रूप से नियंत्रित करने के लिए `Container` इंस्टेंस तक पहुँचें (प्ले, पॉज़, नष्ट करें, इमेज निर्यात करें): + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +export default function ControllableParticles() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFull(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + fpsLimit: 120, + interactivity: { + events: { + onClick: { enable: true, mode: "push" }, + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + push: { quantity: 4 }, + repulse: { distance: 100 }, + }, + }, + particles: { + color: { value: "#ff0000" }, + links: { + enable: true, + color: "#ff0000", + distance: 150, + }, + move: { enable: true, speed: 2 }, + number: { value: 60 }, + size: { value: { min: 1, max: 5 } }, + }, + }), + [], + ); + + const handlePause = useCallback(() => { + containerRef.current?.pause(); + }, []); + + const handlePlay = useCallback(() => { + containerRef.current?.play(); + }, []); + + return ( +
+ +
+ + +
+
+ ); +} +``` + +मुख्य बिंदु: + +- `particlesInit` इंजन सुविधाएँ लोड करता है (प्रति कम्पोनेंट माउंट केवल एक बार चलता है)। +- `particlesLoaded` हर बार फायर होता है जब कंटेनर पूरी तरह से आरंभ हो जाता है। +- `containerRef` `Container` इंस्टेंस रखता है ताकि आप बाद में इसकी विधियाँ कॉल कर सकें। + +## प्रदर्शन: useMemo और useCallback + +कैनवास के अनावश्यक पुनः रेंडर को रोकने के लिए स्थिर या शायद ही बदलने वाले विकल्पों को हमेशा `useMemo` में और इवेंट हैंडलर को `useCallback` में लपेटें: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function PerformanceExample() { + const [particlesCount, setParticlesCount] = useState(80); + + // स्थिर कॉलबैक — डिप्स बदलने तक पुनः नहीं बनता + const particlesLoaded = useCallback((container?: Container) => { + console.log("कंटेनर तैयार", container?.id); + }, []); + + // स्थिर विकल्प ऑब्जेकट — कैनवास पुनः आरंभीकरण रोकता है + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: particlesCount }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [particlesCount], + ); + + return ( +
+ + +
+ ); +} +``` + +इन अनुकूलनों के बिना, प्रत्येक पैरेंट री-रेंडर एक नया `options` ऑब्जेकट बनाएगा, जिससे कैनवास पुनः बनाया जाएगा। + +## पेज इंटीग्रेशन + +पेज सामग्री को प्रभावित किए बिना पेज लेआउट में पार्टिकल पृष्ठभूमि जोड़ें: + +```tsx +// app/layout.tsx (सर्वर कम्पोनेंट) +import dynamic from "next/dynamic"; + +const ParticlesBackground = dynamic(() => import("@/components/particles-background"), { ssr: false }); + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + +
{children}
+ + + ); +} +``` + +`ssr: false` के साथ `dynamic()` का उपयोग करें ताकि सुनिश्चित हो सके कि कम्पोनेंट सर्वर-साइड रेंडरिंग के दौरान कभी न चले। पार्टिकल कैनवास CSS `z-index` के माध्यम से मुख्य सामग्री के पीछे बैठता है। + +## एकाधिक इंस्टेंस + +आप एक ही पेज पर कई स्वतंत्र `Particles` कम्पोनेंट रेंडर कर सकते हैं, प्रत्येक अपने स्वयं के कॉन्फ़िगरेशन के साथ: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +function ParticlesGallery() { + const loaded = useCallback((c?: Container) => {}, []); + + const redOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#1a0000" }, + particles: { + color: { value: "#ff0000" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + const blueOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#00001a" }, + particles: { + color: { value: "#0000ff" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + return ( +
+ + +
+ ); +} +``` + +प्रत्येक `Particles` कम्पोनेंट अपने स्वयं के एनीमेशन लूप के साथ एक स्वतंत्र कैनवास बनाता है। `fullScreen: false` सेट करें और प्रत्येक को एक निश्चित ऊँचाई दें ताकि वे दस्तावेज़ प्रवाह में सह-अस्तित्व में रह सकें। + +## लीगेसी Pages Router + +यदि आप Next.js के **Pages Router** (`pages/` निर्देशिका) का उपयोग कर रहे हैं, तो दृष्टिकोण समान है लेकिन `"use client"` निर्देश के बिना। इसके बजाय, आप पेज कम्पोनेंट में एक डायनामिक इम्पोर्ट का उपयोग कर सकते हैं: + +```tsx +// pages/index.tsx +import dynamic from "next/dynamic"; +import type { NextPage } from "next"; + +const ParticlesComponent = dynamic(() => import("../components/particles-component"), { ssr: false }); + +const Home: NextPage = () => { + return ( +
+ +

स्वागत है

+
+ ); +}; + +export default Home; +``` + +कम्पोनेंट स्वयं (`components/particles-component.tsx`) एक सादा React कम्पोनेंट है: + +```tsx +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesComponent() { + const particlesLoaded = useCallback((container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 80 }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [], + ); + + return ; +} +``` + +ध्यान दें कि Pages Router को `"use client"` की **आवश्यकता नहीं** है क्योंकि पेज कम्पोनेंट डिफ़ॉल्ट रूप से पहले से ही क्लाइंट-रेंडर होते हैं। + +## समस्या निवारण + +| लक्षण | कारण | समाधान | +| ------------------------------ | -------------------------------------------- | ---------------------------------------------------------------------------- | +| खाली सफेद पेज | SSR एक कैनवास-निर्भर मॉड्यूल रेंडर कर रहा है | `dynamic(..., { ssr: false })` का उपयोग करें या क्लाइंट कम्पोनेंट में लपेटें | +| कैनवास नहीं दिख रहा | कंटेनर की ऊँचाई शून्य है | `fullScreen: { zIndex: -1 }` सेट करें या स्पष्ट आयाम दें | +| विकल्प परिवर्तन परिलक्षित नहीं | नया ऑब्जेकट संदर्भ नहीं बनाया गया | उचित डिपेंडेंसी एरे के साथ `useMemo` का उपयोग करें | +| प्रीसेट काम नहीं कर रहा | कंटेनर आरंभ से पहले प्रीसेट लोड नहीं हुआ | `init` कॉलबैक के अंदर `loadXPreset(engine)` कॉल करें | + +## अगले कदम + +- तैयार कॉन्फ़िगरेशन के लिए [इंटरैक्टिव डेमो](/demos/) ब्राउज़ करें। +- हर उपलब्ध पैरामीटर के लिए पूर्ण [विकल्प संदर्भ](/options/) पढ़ें। +- बर्फ, तारे और जुगनू जैसे और अधिक पूर्व-निर्मित प्रीसेट के लिए [प्रीसेट](/demos/presets) पेज देखें। diff --git a/websites/website/docs/hi/guides/nuxt.md b/websites/website/docs/hi/guides/nuxt.md new file mode 100644 index 00000000000..a291d7c5a13 --- /dev/null +++ b/websites/website/docs/hi/guides/nuxt.md @@ -0,0 +1,463 @@ +--- +title: Nuxt इंटीग्रेशन +description: Nuxt 3 / Nuxt 4 एप्लिकेशन में tsParticles को एकीकृत करने के लिए चरण-दर-चरण मार्गदर्शिका। +--- + +# Nuxt इंटीग्रेशन + +यह मार्गदर्शिका आधिकारिक `@tsparticles/vue3` रैपर का उपयोग करके **Nuxt 3** (और Nuxt 4) प्रोजेक्ट में tsParticles को एकीकृत करने को कवर करती है। Nuxt सर्वर-साइड और क्लाइंट-साइड दोनों पर चलता है, इसलिए आपको पार्टिकल कम्पोनेंट को SSR से बचाना होगा। + +## इंस्टॉलेशन + +Vue 3 रैपर और अपनी पसंद का इंजन बंडल इंस्टॉल करें: + +```bash +npm install @tsparticles/vue3 tsparticles +``` + +छोटे बंडल के लिए, `tsparticles` के बजाय `@tsparticles/slim` इंस्टॉल करें: + +```bash +npm install @tsparticles/vue3 @tsparticles/slim +``` + +## मूल उपयोग + +Nuxt कम्पोनेंट को डिफ़ॉल्ट रूप से सर्वर पर रेंडर करता है। चूँकि tsParticles को ब्राउज़र `canvas` API की आवश्यकता है, आपको `` कम्पोनेंट को `` टैग में लपेटना होगा: + +```vue + + + + + +``` + +`` रैपर सुनिश्चित करता है कि `` कम्पोनेंट केवल ब्राउज़र में माउंट हो, जिससे हाइड्रेशन बेमेल को रोका जा सके। + +## कॉन्फ़िगरेशन + +टाइप-सुरक्षित कॉन्फ़िगरेशन के लिए पूर्ण `ISourceOptions` प्रकार का उपयोग करें। आप अपने विकल्पों को इनलाइन परिभाषित कर सकते हैं या उन्हें एक अलग कॉन्फ़िग फ़ाइल से आयात कर सकते हैं: + +```vue + +``` + +## बर्फ प्रभाव + +बर्फ प्रीसेट का उपयोग करके एक सर्दियों की बर्फबारी प्रभाव बनाएँ: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +क्योंकि प्रीसेट ` +``` + +उपलब्ध इंटरैक्शन मोड में शामिल हैं: `grab`, `bubble`, `connect`, `repulse`, `push`, `remove`, `attract`, और `slow`। + +## इवेंट हैंडलिंग + +`` कम्पोनेंट कई लाइफसाइकिल इवेंट उत्सर्जित करता है: + +```vue + + + +``` + +| इवेंट | पेलोड | विवरण | +| -------------------- | ----------- | ------------------------------------------------------------- | +| `@particles-init` | `Engine` | एक बार फायर होता है जब tsParticles इंजन आरंभ होता है | +| `@particles-loaded` | `Container` | हर बार फायर होता है जब कंटेनर लोडिंग या रीलोडिंग पूरी करता है | +| `@particles-destroy` | कोई नहीं | फायर होता है जब कंटेनर नष्ट होता है | + +## पूर्ण टाइपस्क्रिप्ट उदाहरण + +स्पष्ट आयात और लाइफसाइकिल जागरूकता के साथ एक पूर्ण, टाइप किया गया कम्पोनेंट: + +```vue + + + + + +``` + +## पेज इंटीग्रेशन + +कम्पोनेंट को पेज के टेम्पलेट में रखकर किसी विशिष्ट Nuxt पेज में पार्टिकल पृष्ठभूमि जोड़ें: + +```vue + + + + + +``` + +यदि आप **हर** पेज पर पार्टिकल्स चाहते हैं, तो कम्पोनेंट को अलग-अलग पेजों के बजाय `layouts/default.vue` में जोड़ें। + +## Nuxt 4 नोट्स + +Nuxt 4 Nuxt 3 के `` और ` +``` + +## समस्या निवारण + +| लक्षण | कारण | समाधान | +| ------------------------------- | -------------------------------------------- | ------------------------------------------------------------------- | +| खाली स्क्रीन / हाइड्रेशन त्रुटि | `` सर्वर पर रेंडर हुआ | `` में लपेटें | +| प्रीसेट का कोई प्रभाव नहीं | कम्पोनेंट माउंट से पहले प्रीसेट लोड नहीं हुआ | ` + +``` + +इंजन एक बार आरंभ होता है और आपके ऐप में सभी `` इंस्टेंस के बीच साझा होता है। + +--- + +## मूल उपयोग + +इंजन आरंभ करने के बाद, अपने टेम्पलेट में `` कम्पोनेंट का उपयोग करें। कॉन्फ़िगरेशन को JSON-स्ट्रिंगिफ़ाइड ऑब्जेकट या अपने कम्पोनेंट पर एक प्रॉपर्टी के संदर्भ के रूप में पास करें। + +```html + + + + + +``` + +--- + +## सशर्त रेंडरिंग + +पार्टिकल्स कम्पोनेंट के रेंडरिंग में तब तक देरी करने के लिए एक स्थिति प्रॉपर्टी के साथ Riot के `if={}` निर्देश का उपयोग करें जब तक इंजन आरंभीकरण पूरा न हो जाए। यह लेआउट शिफ्ट से बचाता है और सुनिश्चित करता है कि कम्पोनेंट को एक तैयार इंजन प्राप्त हो। + +```html + + + + + +``` + +`this.update()` कॉल करने से एक पुनः रेंडर ट्रिगर होता है ताकि प्रॉमिस हल होने पर `` टैग दिखाई दे। + +--- + +## प्रीसेट उपयोग + +`@tsparticles/configs` पैकेज कॉन्फ़ेटी, आतिशबाज़ी, बर्फ और तारे जैसे सामान्य प्रभावों के लिए पूर्व-निर्मित कॉन्फ़िगरेशन प्रदान करता है। उन्हें सीधे अपने विकल्प ऑब्जेकट के रूप में उपयोग करें। + +```html + + + + + +``` + +उपलब्ध प्रीसेट में `basic`, `confetti`, `fireworks`, `snow`, `stars`, और अधिक शामिल हैं। प्रत्येक प्रीसेट को इंजन कॉलबैक में अपने संबंधित प्रीसेट पैकेज को लोड करने की आवश्यकता होती है। उदाहरण के लिए, `configs.fireworks` को `loadFireworksPreset` की आवश्यकता है। + +--- + +## कस्टम कॉन्फ़िगरेशन + +इंटरैक्टिविटी, एकाधिक आकार और उन्नत एनीमेशन विकल्पों के साथ एक कस्टम कॉन्फ़िगरेशन बनाएँ। + +```html + + + + + +``` + +--- + +## पूर्ण कम्पोनेंट + +नीचे एक पूर्ण `.riot` फ़ाइल है जो सब कुछ एक साथ जोड़ती है: `onBeforeMount` में इंजन आरंभीकरण, स्थिति के साथ सशर्त रेंडरिंग, इंटरैक्टिविटी के साथ एक समृद्ध कॉन्फ़िगरेशन, और लोडेड इवेंट के लिए कम्पोनेंट के अंतर्निहित समर्थन के माध्यम से एक `particlesLoaded` कॉलबैक। + +```html + +
+

tsParticles + Riot.js

+ + {#if state.particlesInitialized} + + {:else} +

पार्टिकल इंजन लोड हो रहा है...

+ {/if} +
+ + + + +
+``` + +--- + +आपके पास अब Riot.js एप्लिकेशन में tsParticles को एकीकृत करने के लिए आवश्यक सब कुछ है। प्रत्येक उदाहरण आत्मनिर्भर है और आपके प्रोजेक्ट में कॉपी करने के लिए तैयार है। diff --git a/websites/website/docs/hi/guides/solid.md b/websites/website/docs/hi/guides/solid.md new file mode 100644 index 00000000000..0d2a2445240 --- /dev/null +++ b/websites/website/docs/hi/guides/solid.md @@ -0,0 +1,512 @@ +--- +title: SolidJS इंटीग्रेशन +description: आधिकारिक @tsparticles/solid रैपर का उपयोग करके SolidJS एप्लिकेशन में tsParticles को एकीकृत करने के लिए चरण-दर-चरण मार्गदर्शिका। +--- + +# SolidJS इंटीग्रेशन + +यह मार्गदर्शिका आधिकारिक `@tsparticles/solid` रैपर का उपयोग करके **SolidJS** प्रोजेक्ट में tsParticles को एकीकृत करने को कवर करती है। SolidJS का बारीक-दाने वाला रिएक्टिविटी मॉडल tsParticles के साथ अच्छी तरह से काम करता है — विकल्प परिवर्तन पूर्ण पुनः आरंभीकरण के बिना लक्षित कैनवास अपडेट ट्रिगर करते हैं। + +## इंस्टॉलेशन + +SolidJS रैपर और अपनी पसंद का इंजन बंडल इंस्टॉल करें: + +```bash +npm install @tsparticles/solid tsparticles +``` + +छोटे बंडल के लिए, इसके बजाय `@tsparticles/slim` का उपयोग करें: + +```bash +npm install @tsparticles/solid @tsparticles/slim +``` + +## मूल उपयोग + +SolidJS पूरी तरह से ब्राउज़र में चलता है (कोई SSR नहीं), इसलिए आपको सर्वर रेंडरिंग के खिलाफ गार्ड करने की आवश्यकता नहीं है। हालाँकि, पार्टिकल्स रेंडर करने से पहले इंजन को एसिंक रूप से आरंभ किया जाना चाहिए। + +इंजन सुविधाएँ लोड करने के लिए `onMount` के अंदर `initParticlesEngine` का उपयोग करें, फिर `` के साथ सशर्त रूप से `` कम्पोनेंट रेंडर करें: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [initialized, setInitialized] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setInitialized(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +`` कम्पोनेंट सुनिश्चित करता है कि `` एलिमेंट इंजन तैयार होने के बाद ही DOM में डाला जाए। + +## इंजन आरंभीकरण + +`initParticlesEngine` फ़ंक्शन एक कॉलबैक स्वीकार करता है जो `Engine` इंस्टेंस प्राप्त करता है। अपने कॉन्फ़िगरेशन को आवश्यक सुविधाओं को पंजीकृत करने के लिए इस कॉलबैक का उपयोग करें: + +```tsx +import { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import { loadSlim } from "@tsparticles/slim"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Engine } from "@tsparticles/engine"; + +// न्यूनतम — केवल मूल आकार और हलचल +initParticlesEngine((engine: Engine) => loadSlim(engine)).then(() => { + console.log("इंजन तैयार (स्लिम)"); +}); + +// पूर्ण — हर सुविधा शामिल +initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => { + console.log("इंजन तैयार (पूर्ण)"); +}); + +// केवल प्रीसेट — एक विशिष्ट प्रीसेट के लिए आवश्यक सुविधाएँ +initParticlesEngine((engine: Engine) => loadConfettiPreset(engine)).then(() => { + console.log("कॉन्फ़ेटी प्रीसेट लोड हुआ"); +}); +``` + +`initParticlesEngine` को अपने ऐप में एक बार कॉल करें — आमतौर पर रूट कम्पोनेंट के `onMount` में। इंजन इंस्टेंस कैश हो जाता है, इसलिए बाद के कॉल तुरंत लौट आते हैं। + +## सशर्त रेंडरिंग + +इंजन आरंभ होने तक रेंडरिंग स्थगित करने के लिए SolidJS के `` नियंत्रण प्रवाह का उपयोग करें: + +```tsx +import { createSignal, Show, onMount } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import type { Engine } from "@tsparticles/engine"; +import type { Component } from "solid-js"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + पार्टिकल्स लोड हो रहे हैं...

}> + +
+ ); +}; +``` + +`fallback` प्रॉप इंजन आरंभ होने के दौरान एक लोडिंग संकेतक दिखाता है। + +## प्रीसेट उपयोग + +त्वरित, पूर्व-डिज़ाइन किए गए कॉन्फ़िगरेशन के लिए `@tsparticles/configs` का उपयोग करें: + +```bash +npm install @tsparticles/configs +``` + +```tsx +import configs from "@tsparticles/configs"; +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + +
+ + +
+
+ ); +}; + +export default App; +``` + +उपलब्ध कॉन्फ़िग में शामिल हैं: `basic`, `bubbles`, `snow`, `stars`, `fireworks`, `confetti`, `links`, और अधिक। + +## इंटरैक्टिव पार्टिकल्स + +`interactivity` अनुभाग कॉन्फ़िगर करके क्लिक और होवर इंटरैक्शन जोड़ें: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 60 }, + links: { enable: true, distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 4 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +- **होवर मोड**: `grab`, `bubble`, `repulse`, `attract`, `slow`, `connect` +- **क्लिक मोड**: `push`, `remove`, `repulse`, `bubble`, `attract`, `pause` + +## कस्टम कॉन्फ़िगरेशन + +एकाधिक पार्टिकल आकार, रंग पैलेट और गति सेटिंग्स के साथ एक पूर्ण कस्टम कॉन्फ़िगरेशन: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0a0a23" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { enable: true, rotateX: 600, rotateY: 1200 }, + }, + number: { + value: 40, + density: { enable: true }, + }, + opacity: { + value: { min: 0.3, max: 0.8 }, + animation: { + enable: true, + speed: 0.5, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + animation: { + enable: true, + speed: 2, + sync: false, + }, + }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.3, + width: 1, + }, + shape: { + type: ["circle", "square", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + twinkle: { + particles: { + enable: true, + frequency: 0.05, + opacity: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "bubble" }, + }, + modes: { + repulse: { distance: 120 }, + bubble: { distance: 200, size: 10, opacity: 0.8 }, + }, + }, + detectRetina: true, + }; + + return ( + + + + ); +}; + +export default App; +``` + +## पूर्ण टाइपस्क्रिप्ट उदाहरण + +कंटेनर संदर्भ, इंजन आरंभीकरण और मैन्युअल नियंत्रण के साथ एक पूर्ण टाइप किया गया कम्पोनेंट: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [container, setContainer] = createSignal(undefined); + const [paused, setPaused] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#1a1a2e" }, + particles: { + color: { value: "#e94560" }, + number: { value: 80 }, + links: { enable: true, color: "#e94560", distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 5 } }, + }, + }; + + const particlesLoaded = (c: Container) => { + setContainer(c); + }; + + const togglePause = () => { + const c = container(); + if (c) { + if (paused()) { + c.play(); + } else { + c.pause(); + } + setPaused(!paused()); + } + }; + + return ( + + + + + ); +}; + +export default App; +``` + +## सिग्नल के साथ डायनामिक विकल्प + +SolidJS की ताकतों में से एक बारीक-दाने वाली रिएक्टिविटी है — आप पार्टिकल विकल्पों को चलाने के लिए सिग्नल का उपयोग कर सकते हैं और कैनवास कुशलतापूर्वक अपडेट होगा: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [color, setColor] = createSignal("#ff0000"); + const [particleCount, setParticleCount] = createSignal(60); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + // विकल्प एक नियमित ऑब्जेकट हैं — इसे Particles कम्पोनेंट के + // आंतरिक ट्रैकिंग के माध्यम से प्रतिक्रियाशील रूप से पढ़ा जाएगा + const options = (): ISourceOptions => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#000" }, + particles: { + color: { value: color() }, + number: { value: particleCount() }, + links: { enable: true, color: color() }, + move: { enable: true }, + }, + }); + + return ( + + {}} /> +
+ + +
+
+ ); +}; + +export default App; +``` + +क्योंकि `options` एक फ़ंक्शन है जो सिग्नल तक पहुँचता है, हर बार `color()` या `particleCount()` बदलने पर, `` कम्पोनेंट एक नया विकल्प ऑब्जेकट प्राप्त करता है और मौजूदा कैनवास पर केवल बदली हुई प्रॉपर्टी लागू करता है। + +## कस्टम ओवरराइड के साथ प्रीसेट + +एक प्रीसेट लोड करें, फिर एक अनुकूलित प्रभाव के लिए कस्टम ओवरराइड मर्ज करें: + +```tsx +import { loadSnowPreset } from "@tsparticles/preset-snow"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadSnowPreset(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + preset: "snow", + fullScreen: { zIndex: -1 }, + background: { color: "#0d0d2b" }, + particles: { + // बर्फ के रंग को नीला करने के लिए ओवरराइड करें + color: { value: "#88ccff" }, + // बर्फ के टुकड़ों की संख्या बढ़ाएँ + number: { value: 300 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +प्रीसेट प्रत्येक विकल्प के लिए डिफ़ॉल्ट मान प्रदान करता है, और आपके ओवरराइड शीर्ष पर मर्ज हो जाते हैं — आपको केवल उन प्रॉपर्टी को निर्दिष्ट करने की आवश्यकता है जिन्हें आप बदलना चाहते हैं। + +## समस्या निवारण + +| लक्षण | कारण | समाधान | +| ------------------------------ | --------------------------------------- | -------------------------------------------------------------------------------- | +| खाली DOM एलिमेंट | रेंडर से पहले इंजन आरंभ नहीं हुआ | `` को `` में लपेटें | +| कोई पार्टिकल्स दिखाई नहीं देते | `move.enable` या `number.value` गायब है | सुनिश्चित करें `particles.move.enable: true` और `particles.number.value > 0` | +| कैनवास सामग्री के पीछे | fullScreen में `zIndex` गायब है | `fullScreen: { zIndex: -1 }` का उपयोग करें | +| विकल्प परिवर्तन परिलक्षित नहीं | ऑब्जेकट संदर्भ नहीं बदल रहा | विकल्पों को फ़ंक्शन या स्टोर में लपेटें; स्थिर ऑब्जेकट से बचें | +| इंजन नहीं मिला | `loadFull` या `loadSlim` आयात गायब | `tsparticles` या `@tsparticles/slim` इंस्टॉल करें और `loadFull(engine)` कॉल करें | + +## अगले कदम + +- उपयोग के लिए तैयार कॉन्फ़िगरेशन के लिए [कॉन्फ़िग प्लेग्राउंड](/playground/configs) देखें। +- पैरामीटर की पूरी सूची के लिए [विकल्प संदर्भ](/options/) पढ़ें। +- GitHub पर रैपर आंतरिक के लिए [SolidJS स्रोत](https://github.com/tsparticles/solid) देखें। diff --git a/websites/website/docs/hi/guides/stencil.md b/websites/website/docs/hi/guides/stencil.md new file mode 100644 index 00000000000..7ee98e9359b --- /dev/null +++ b/websites/website/docs/hi/guides/stencil.md @@ -0,0 +1,359 @@ +--- +title: स्टेंसिल गाइड +description: स्टेंसिल कम्पोनेंट के साथ tsParticles को एकीकृत करने के लिए पूर्ण मार्गदर्शिका। +--- + +# स्टेंसिल गाइड + +## विषय सूची + +1. [इंस्टॉलेशन](#installation) +2. [कस्टम एलिमेंट पंजीकरण](#custom-elements-registration) +3. [मूल उपयोग](#basic-usage) +4. [इंजन आरंभीकरण](#engine-initialization) +5. [कस्टम कॉन्फ़िगरेशन](#custom-configuration) +6. [कम्पोनेंट लाइफसाइकिल](#component-lifecycle) +7. [टाइपस्क्रिप्ट उदाहरण](#typescript-example) + +--- + +## इंस्टॉलेशन + +स्टेंसिल रैपर और tsParticles इंजन को npm के माध्यम से इंस्टॉल करें: + +```bash +npm install @tsparticles/stencil tsparticles +``` + +वैकल्पिक रूप से मैन्युअल कॉन्फ़िगरेशन कम करने के लिए एक प्रीसेट बंडल इंस्टॉल करें: + +```bash +npm install @tsparticles/slim +``` + +--- + +## कस्टम एलिमेंट पंजीकरण + +`@tsparticles/stencil` पैकेज एक `defineCustomElements` फ़ंक्शन प्रदान करता है जो `` कस्टम एलिमेंट को ब्राउज़र के साथ पंजीकृत करता है। अपने ऐप में कहीं भी कम्पोनेंट का उपयोग करने से पहले इसे एक बार कॉल करें। + +```tsx +import { defineCustomElements } from "@tsparticles/stencil/loader"; + +// एलिमेंट पंजीकृत करें +defineCustomElements(); +``` + +लेज़ी-लोडिंग का उपयोग करने वाले स्टेंसिल प्रोजेक्ट के लिए, रेंडरिंग से पहले एलिमेंट उपलब्ध होना सुनिश्चित करने के लिए इसे `componentWillLoad` या अपने ऐप के रूट कम्पोनेंट में कॉल करें। + +--- + +## मूल उपयोग + +एक बार कस्टम एलिमेंट पंजीकृत हो जाने पर, आप आवश्यक इंजन सुविधाओं को लोड करने के लिए `options` प्रॉप और `init` कॉलबैक के साथ अपने JSX में `` का उपयोग कर सकते हैं। + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +@Component({ tag: "my-particles" }) +export class MyParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## इंजन आरंभीकरण + +`init` प्रॉप इंजन इंस्टेंस प्राप्त करता है और आपको आवश्यक सुविधाएँ लोड करने देता है। यह `loadSlim`, `loadFull`, या व्यक्तिगत अपडेटर/इंटरैक्शन प्लगइन कॉल करने के लिए अनुशंसित स्थान है। + +```tsx +import { loadSlim } from "@tsparticles/slim"; +import { loadFull } from "tsparticles"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// विकल्प A: हल्का (वृत्त, मूल हलचल, लिंक) +init={async engine => { await loadSlim(engine); }} + +// विकल्प B: पूर्ण सुविधा सेट (सभी आकार, प्रभाव, प्रीसेट) +init={async engine => { await loadFull(engine); }} + +// विकल्प C: प्रीसेट (कॉन्फ़ेटी, आतिशबाज़ी, बर्फ, तारे) +init={async engine => { await loadConfettiPreset(engine); }} +``` + +इंजन इंस्टेंस आरंभीकरण के बाद `container-id` विशेषता के माध्यम से भी पहुँच योग्य है, जिससे यदि आवश्यक हो तो बाद में पार्टिकल सिस्टम को प्रोग्रामेटिक रूप से नियंत्रित किया जा सकता है। + +--- + +## कस्टम कॉन्फ़िगरेशन + +नीचे इंटरैक्टिविटी, एकाधिक आकार प्रकार और होवर/क्लिक मोड के साथ एक पूर्ण कॉन्फ़िगरेशन है। + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const fullOptions: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { + color: "#0f0f23", + }, +}; + +@Component({ tag: "app-particles" }) +export class AppParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## कम्पोनेंट लाइफसाइकिल + +स्टेंसिल में, एकमुश्त सेटअप के लिए अनुशंसित लाइफसाइकिल हुक `componentWillLoad` है। इसका उपयोग कस्टम एलिमेंट पंजीकृत करने और आरंभीकरण स्थिति प्रबंधित करने के लिए करें ताकि `` कम्पोनेंट केवल तब रेंडर हो जब इंजन तैयार हो। + +```tsx +import { Component, h, State } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ tag: "app-root" }) +export class AppRoot { + @State() private engineReady = false; + + private options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { + enable: true, + speed: 1, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#1a1a2e" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.engineReady = true; + } + + render() { + return ( +
+

tsParticles + स्टेंसिल

+ {this.engineReady && ( + { + await loadSlim(engine); + }} + /> + )} +
+ ); + } +} +``` + +`@State()` का उपयोग यह सुनिश्चित करता है कि इंजन तैयार होने पर कम्पोनेंट पुनः रेंडर होता है, और सशर्त रेंडर कस्टम एलिमेंट परिभाषित होने से पहले पार्टिकल्स कंटेनर को माउंट होने से रोकता है। + +--- + +## टाइपस्क्रिप्ट उदाहरण + +यहाँ एक पूर्ण, टाइप किया गया स्टेंसिल एप्लिकेशन कम्पोनेंट है जो स्लिम प्रीसेट, होवर इंटरैक्टिविटी और एक कस्टम डार्क थीम के साथ tsParticles को एकीकृत करता है। + +```tsx +import { Component, h, State, Prop } from "@stencil/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ + tag: "app-home", + styleUrl: "app-home.css", + shadow: true, +}) +export class AppHome { + @State() private initialized = false; + + @Prop() readonly title: string = "स्वागत है"; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.initialized = true; + } + + private handleInit = async (engine: Engine): Promise => { + await loadSlim(engine); + }; + + private handleLoaded = async (container?: Container): Promise => { + this.container = container; + console.log("पार्टिकल्स कंटेनर लोड हुआ:", container?.id); + }; + + render() { + return ( +
+

{this.title}

+

tsParticles और स्टेंसिल द्वारा संचालित

+ + {this.initialized && ( + + )} +
+ ); + } +} +``` + +`particlesLoaded` इवेंट पहला फ्रेम रेंडर होने पर फायर होता है, जो आपको प्रोग्रामेटिक नियंत्रण (प्ले, पॉज़, स्टॉप, थीम स्विच) के लिए `Container` इंस्टेंस तक पहुँच प्रदान करता है। + +--- + +आपके पास अब स्टेंसिल एप्लिकेशन में tsParticles को एकीकृत करने के लिए आवश्यक सब कुछ है। प्रत्येक उदाहरण आत्मनिर्भर है और आपके प्रोजेक्ट में कॉपी करने के लिए तैयार है। diff --git a/websites/website/docs/hi/guides/svelte.md b/websites/website/docs/hi/guides/svelte.md new file mode 100644 index 00000000000..564bcc9e9ce --- /dev/null +++ b/websites/website/docs/hi/guides/svelte.md @@ -0,0 +1,580 @@ +--- +title: Svelte इंटीग्रेशन +description: "@tsparticles/svelte का उपयोग करके Svelte और SvelteKit एप्लिकेशन में tsParticles को एकीकृत करने के लिए चरण-दर-चरण मार्गदर्शिका।" +--- + +# Svelte इंटीग्रेशन + +`@tsparticles/svelte` पैकेज tsParticles के लिए एक देशी Svelte कम्पोनेंट प्रदान करता है। यह मार्गदर्शिका Svelte (Vite के साथ) और SvelteKit को कवर करती है, जिसमें रिएक्टिव विकल्प, इवेंट हैंडलिंग और एकाधिक इंस्टेंस शामिल हैं। + +--- + +## इंस्टॉलेशन + +```bash +npm install @tsparticles/svelte @tsparticles/engine +``` + +पूर्ण बंडल या प्रीसेट के लिए: + +```bash +npm install tsparticles +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +``` + +--- + +## मूल उपयोग + +```svelte + + + +``` + +--- + +## इंजन आरंभीकरण + +अपने ऐप को आवश्यक प्लगइन और प्रीसेट लोड करने के लिए एक `on:init` इवेंट हैंडलर पास करें: + +```svelte + + + +``` + +वैकल्पिक रूप से, माउंट करने से पहले `initParticlesEngine` उपयोगिता का उपयोग करें: + +```svelte + + +{#if ready} + +{/if} +``` + +--- + +## बर्फ प्रभाव + +```bash +npm install @tsparticles/preset-snow +``` + +```svelte + + + +``` + +अतिरिक्त विकल्पों को मर्ज करके प्रीसेट व्यवहार को अनुकूलित करें: + +```svelte + +``` + +--- + +## तारे प्रभाव + +```bash +npm install @tsparticles/preset-stars +``` + +```svelte + + + +``` + +--- + +## इंटरैक्टिव पार्टिकल्स + +माउस होवर और क्लिक इंटरैक्टिविटी जोड़ें: + +```svelte + + + +``` + +--- + +## इवेंट हैंडलिंग + +```svelte + + +
+ + + +
+ + +``` + +| इवेंट | विवरण | फायर होता है | +| -------------------- | ----------- | --------------------------------- | +| `on:init` | `Engine` | इंजन आरंभ होने के बाद | +| `on:particlesLoaded` | `Container` | कंटेनर पूरी तरह तैयार होने के बाद | + +--- + +## टाइपस्क्रिप्ट उदाहरण + +पूर्ण टाइप किया गया कम्पोनेंट: + +```svelte + + + +``` + +--- + +## डायनामिक विकल्प + +रिएक्टिव विकल्प इंस्टेंस को पुनः बनाए बिना पार्टिकल्स को अपडेट करते हैं: + +```svelte + + +
+ +
+ + +``` + +`$:` प्रतिक्रियाशील घोषणा हर बार `color` बदलने पर `options` की पुनर्गणना करती है, और `Particles` कम्पोनेंट स्वचालित रूप से नया कॉन्फ़िगरेशन लेता है। + +--- + +## एकाधिक इंस्टेंस + +एक ही पेज पर कई स्वतंत्र पार्टिकल सिस्टम रेंडर करें: + +```svelte + + +
+
+ +
+
+ +
+
+``` + +प्रत्येक `` कम्पोनेंट को अपना स्वयं का `id`, कैनवास और इंजन संदर्भ मिलता है। + +--- + +## SvelteKit उपयोग + +SvelteKit में, कैनवास को ब्राउज़र वातावरण की आवश्यकता है। कम्पोनेंट के लिए SSR अक्षम करें: + +```svelte + + +{#if Component} + +{/if} +``` + +या आयात को क्लाइंट-ओनली कम्पोनेंट में लपेटें। SvelteKit 2+ के लिए, आप `vite-plugin-svelte` SSR बहिष्करण का भी उपयोग कर सकते हैं। + +--- + +## API संदर्भ + +| प्रॉप | प्रकार | डिफ़ॉल्ट | विवरण | +| --------- | ---------------- | --------------- | ----------------------------- | +| `id` | `string` | `"tsparticles"` | कैनवास एलिमेंट आईडी | +| `options` | `ISourceOptions` | `{}` | पार्टिकल कॉन्फ़िगरेशन ऑब्जेकट | +| `url` | `string` | — | दूरस्थ JSON कॉन्फ़िग का URL | + +| इवेंट | विवरण | विवरण | +| -------------------- | ----------- | ------------------------------------------------------------------------ | +| `on:init` | `Engine` | जब इंजन आरंभ होता है तब फायर होता है (प्लगइन लोड करने के लिए उपयोग करें) | +| `on:particlesLoaded` | `Container` | जब कंटेनर पूरी तरह तैयार होता है तब फायर होता है | + +--- + +## समस्या निवारण + +- **कैनवास दिखाई नहीं देता** — सुनिश्चित करें कि पैरेंट कंटेनर में स्पष्ट आयाम हों (`height: 100%`, `height: 100vh`, या एक निश्चित पिक्सेल मान)। +- **`loadFull is not a function`** — सत्यापित करें कि `tsparticles` इंस्टॉल है और आप `tsparticles` से `loadFull` आयात कर रहे हैं (`@tsparticles/engine` से नहीं)। +- **रिएक्टिविटी काम नहीं कर रही** — सुनिश्चित करें कि `options` एक प्रतिक्रियाशील चर है (`$:` या `let` एक प्रतिक्रियाशील स्रोत से बंधा)। सादे `const` मान अपडेट नहीं होंगे। +- **SvelteKit खाली स्क्रीन** — `@tsparticles/svelte` को डायनामिक रूप से आयात करें या ऊपर SvelteKit अनुभाग में दिखाए अनुसार `browser` गार्ड का उपयोग करें। +- **`event.detail` के लिए टाइपस्क्रिप्ट त्रुटियाँ** — इवेंट हैंडलर के लिए `CustomEvent` और `CustomEvent` प्रकार का उपयोग करें। diff --git a/websites/website/docs/hi/guides/vanilla.md b/websites/website/docs/hi/guides/vanilla.md new file mode 100644 index 00000000000..08be0829c5f --- /dev/null +++ b/websites/website/docs/hi/guides/vanilla.md @@ -0,0 +1,889 @@ +--- +title: वैनिला JS गाइड +description: सादे जावास्क्रिप्ट के साथ tsParticles को एकीकृत करने के लिए पूर्ण गाइड। +--- + +# वैनिला JS गाइड + +## विषय-सूची + +1. [आरंभ करना](#getting-started) +2. [मूल कण](#basic-particles) +3. [कॉन्फ़ेटी प्रभाव](#confetti-effect) +4. [आतिशबाजी प्रभाव](#fireworks-effect) +5. [रिबन प्रभाव](#ribbons-effect) +6. [हिम प्रभाव](#snow-effect) +7. [नेटवर्क / लिंक्स प्रभाव](#network-links-effect) +8. [तारे प्रभाव](#stars-effect) +9. [कस्टम कॉन्फ़िगरेशन](#custom-configuration) +10. [एकाधिक कंटेनर](#multiple-containers) +11. [डायनामिक नियंत्रण](#dynamic-controls) + +--- + +## आरंभ करना + +### CDN (त्वरित आरंभ) + +अपने HTML में एक `
` प्लेसहोल्डर और स्क्रिप्ट टैग जोड़ें। आपको कम से कम इंजन + एक बंडल की आवश्यकता है, और `tsParticles.load()` से पहले लोडर को कॉल करना होगा। + +```html + + + + + + tsParticles – आरंभ करना + + + +
+ + + + + + +``` + +### npm + +```bash +npm install @tsparticles/engine @tsparticles/slim +``` + +फिर इसे आयात करें और उपयोग करें: + +```javascript +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +(async () => { + await loadSlim(tsParticles); + + await tsParticles.load({ + id: "tsparticles", + options: { + /* ... */ + }, + }); +})(); +``` + +> **नोट:** `@tsparticles/engine` अकेला कुछ नहीं बनाता। दृश्य आकार प्राप्त करने के लिए आपको एक बंडल (`@tsparticles/slim` अनुशंसित) या व्यक्तिगत प्लगइन्स स्थापित करना होगा। + +--- + +## मूल कण + +एक न्यूनतम कॉन्फ़िगरेशन जो 100 कणों को गोलाकार आकार, यादृच्छिक रंग और हल्की गति के साथ प्रस्तुत करता है। v4 में, कण रंग पुराने `color` गुण के बजाय `paint` के माध्यम से सेट किए जाते हैं। + +```html + + + + + + मूल कण + + + +
+ + + + + + +``` + +--- + +## कॉन्फ़ेटी प्रभाव + +एक उत्सवपूर्ण विस्फोट के लिए समर्पित `@tsparticles/confetti` बंडल का उपयोग करें, जो एक ही फ़ंक्शन कॉल से काम करता है। + +```html + + + + + + कॉन्फ़ेटी + + + + + + + + + +``` + +--- + +## आतिशबाजी प्रभाव + +ध्वनि प्रभावों के साथ समर्पित `@tsparticles/fireworks` बंडल का उपयोग करके एक आतिशबाजी प्रदर्शन। + +```html + + + + + + आतिशबाजी + + + + + + + +``` + +--- + +## रिबन प्रभाव + +प्रवाहमान रिबन एनिमेशन के लिए समर्पित `@tsparticles/ribbons` बंडल का उपयोग करें जो माउस की स्थिति पर प्रतिक्रिया करते हैं। + +```html + + + + + + रिबन + + + + + + + +``` + +--- + +## हिम प्रभाव + +`@tsparticles/configs` प्रीसेट कैटलॉग का उपयोग करके हल्के से गिरते बर्फ के टुकड़े। + +```html + + + + + + हिम प्रभाव + + + +
+ + + + + + + +``` + +वैकल्पिक रूप से, स्वतंत्र प्रीसेट पैकेज का उपयोग करके: + +```html + + + + +``` + +--- + +## नेटवर्क / लिंक्स प्रभाव + +माउस इंटरैक्टिविटी के साथ एक क्लासिक कनेक्टेड-नोड्स विज़ुअल। `@tsparticles/slim` बंडल में लिंक्स इंटरैक्शन और माउस ग्रैब मोड शामिल है। + +```html + + + + + + नेटवर्क / लिंक्स + + + +
+ + + + + + +``` + +--- + +## तारे प्रभाव + +`@tsparticles/configs` प्रीसेट कैटलॉग का उपयोग करके एक तारों भरा रात का आकाश। + +```html + + + + + + तारे प्रभाव + + + +
+ + + + + + + +``` + +वैकल्पिक रूप से, स्वतंत्र प्रीसेट पैकेज का उपयोग करके: + +```html + + + + +``` + +--- + +## कस्टम कॉन्फ़िगरेशन + +स्लिम बंडल का उपयोग करके ग्रेडिएंट बैकग्राउंड, इंटरैक्टिव होवर प्रभाव और एकाधिक आकार प्रकारों के साथ स्क्रैच से एक कॉन्फ़िगरेशन बनाएं। + +```html + + + + + + कस्टम कॉन्फ़िग + + + +

कस्टम कॉन्फ़िगरेशन

+
+ + + + + + +``` + +--- + +## एकाधिक कंटेनर + +एक ही पेज पर अनेक स्वतंत्र कण इंस्टेंस चलाएं, प्रत्येक का अपना कॉन्फ़िगरेशन होता है। + +```html + + + + + + एकाधिक कंटेनर + + + +
+
+
+
+ + + + + + +``` + +--- + +## डायनामिक नियंत्रण + +प्रोग्रामेटिक रूप से रनटाइम पर प्रारंभ करें, रोकें, थामें और थीम बदलें। + +```html + + + + + + डायनामिक नियंत्रण + + + +
+
+ + + + + + +
+ + + + + + +``` + +--- + +अब आपने tsParticles v4 के लिए हर प्रमुख वैनिला JS एकीकरण पैटर्न को कवर कर लिया है। प्रत्येक उदाहरण एक स्वतंत्र HTML फ़ाइल है जिसे आप अपने ब्राउज़र में खोलकर tsParticles को क्रियाशील देख सकते हैं। diff --git a/websites/website/docs/hi/guides/vue3.md b/websites/website/docs/hi/guides/vue3.md new file mode 100644 index 00000000000..bcb880393fc --- /dev/null +++ b/websites/website/docs/hi/guides/vue3.md @@ -0,0 +1,622 @@ +--- +title: Vue 3 एकीकरण +description: "@tsparticles/vue3 का उपयोग करके Vue 3 अनुप्रयोगों में tsParticles को एकीकृत करने के लिए चरण-दर-चरण मार्गदर्शिका।" +--- + +# Vue 3 एकीकरण + +`@tsparticles/vue3` पैकेज tsParticles के लिए एक मूल Vue 3 घटक और प्लगइन प्रणाली प्रदान करता है। यह मार्गदर्शिका मूल सेटअप से लेकर डायनामिक थीम स्विचिंग और कस्टम प्रीसेट जैसे उन्नत पैटर्न तक सब कुछ कवर करती है। + +--- + +## स्थापना + +```bash +npm install @tsparticles/vue3 @tsparticles/engine +``` + +वैकल्पिक रूप से कोई प्रीसेट या पूर्ण बंडल स्थापित करें: + +```bash +# पूर्ण बंडल (सभी सुविधाएँ) +npm install tsparticles + +# विशिष्ट प्रीसेट +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars + +# उपयोगिता कॉन्फ़िग +npm install @tsparticles/configs +``` + +--- + +## मूल उपयोग + +अपने ऐप एंट्री पॉइंट में प्लगइन पंजीकृत करें, फिर `` घटक का कहीं भी उपयोग करें। + +### ऐप एंट्री (`main.ts`) + +```typescript +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +const app = createApp(App); + +app.use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, +}); + +app.mount("#app"); +``` + +### घटक (`App.vue`) + +```vue + + + +``` + +--- + +## घटक के साथ `particlesInit` का उपयोग + +यदि आप वैश्विक प्लगइन का उपयोग नहीं करना चाहते हैं, तो सीधे `init` कॉलबैक पास करें: + +```vue + + + +``` + +--- + +## ईवेंट + +घटक कई जीवनचक्र ईवेंट उत्सर्जित करता है: + +```vue + + + +``` + +--- + +## कॉन्फ़ेटी प्रभाव + +उत्सवों के लिए कॉन्फ़ेटी प्रीसेट का उपयोग करें: + +```bash +npm install @tsparticles/preset-confetti +``` + +```vue + + + +``` + +एक बार के विस्फोट के लिए, प्रीसेट लोड करें फिर किसी विधि के अंदर प्रोग्रामेटिक रूप से `tsParticles.load()` कॉल करें। + +--- + +## आतिशबाजी प्रभाव + +आतिशबाजी प्रीसेट उच्च-प्रभाव वाले कण विस्फोट बनाता है: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```vue + + + +``` + +> **टिप:** आतिशबाजी प्रीसेट संसाधन-गहन है। इसे घटक से बंधे `v-if` को टॉगल करके उपयोगकर्ता इंटरैक्शन (जैसे, बटन क्लिक) पर ट्रिगर करें। + +--- + +## बर्फ प्रभाव + +बर्फ प्रीसेट के साथ गिरती बर्फ का अनुकरण करें: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +--- + +## इंटरैक्टिव कण + +होवर और क्लिक इंटरैक्टिविटी मोड जोड़ें: + +```vue + + + +``` + +उपलब्ध इंटरैक्शन मोड: `grab`, `repulse`, `bubble`, `connect`, `push`, `remove`, `trail`, `attract`, `light`. + +--- + +## थीम स्विचिंग + +रिएक्टिव ऑप्शन ऑब्जेक्ट को अपडेट करके रनटाइम पर कण थीम को गतिशील रूप से बदलें: + +```vue + + + +``` + +वैकल्पिक रूप से, शून्य-कॉन्फ़िग स्विचिंग के लिए अंतर्निहित [themes](https://particles.js.org/docs/interfaces/Options_Interfaces_IOptions.IOptions.html#themes) विकल्प और कंटेनर पर `theme` प्रॉपर्टी का उपयोग करें। + +--- + +## @tsparticles/configs से कस्टम प्रीसेट + +`@tsparticles/configs` पैकेज पूर्व-निर्मित कॉन्फ़िगरेशन ऑब्जेक्ट निर्यात करता है: + +```bash +npm install @tsparticles/configs +``` + +```vue + + + +``` + +तैयार-से-उपयोग लेआउट के लिए `@tsparticles/configs` पैकेज में उपलब्ध कॉन्फ़िग देखें। + +--- + +## इंजन आरंभीकरण दृष्टिकोण + +इंजन को आरंभ करने के दो तरीके हैं: + +### 1. वैश्विक प्लगइन (अनुशंसित) + +```typescript +// main.ts +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +createApp(App) + .use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, + }) + .mount("#app"); +``` + +इंजन फिर वैश्विक रूप से उपलब्ध है और सभी `` इंस्टेंस इसे साझा करते हैं। + +### 2. घटक-स्तरीय आरंभीकरण + +प्रत्येक `` इंस्टेंस को एक `:init` कॉलबैक पास करें। तब उपयोगी जब विभिन्न घटकों को विभिन्न प्लगइन सेट की आवश्यकता हो: + +```vue + +``` + +### 3. पार्टिकल्स प्रोवाइडर (कम्पोज़िशन API) + +इंजन तक प्रोग्रामेटिक रूप से पहुँचने के लिए प्रोवाइडर का उपयोग करें: + +```vue + +``` + +--- + +## नामित निर्यात + TypeScript + +सभी भागों के साथ पूर्ण TypeScript उदाहरण: + +```vue + + + +``` + +--- + +## API संदर्भ + +| प्रॉप | प्रकार | डिफ़ॉल्ट | विवरण | +| --------- | ----------------------------------- | --------------- | ----------------------------- | +| `id` | `string` | `"tsparticles"` | कैनवास तत्व आईडी | +| `options` | `ISourceOptions` | `{}` | कण कॉन्फ़िगरेशन | +| `init` | `(engine: Engine) => Promise` | — | इंजन आरंभीकरण कॉलबैक | +| `url` | `string` | — | JSON कॉन्फ़िग लोड करने का URL | + +| ईवेंट | पेलोड | विवरण | +| ------------------- | ----------- | --------------------------------------------------------- | +| `@particles-loaded` | `Container` | जब कंटेनर पूरी तरह से आरंभीकृत हो जाता है तब फायर होता है | +| `@particles-init` | `Engine` | इंजन आरंभीकृत होने के बाद फायर होता है | + +--- + +## समस्या निवारण + +- **त्रुटि: `tsparticles is not defined`** — सुनिश्चित करें कि घटक रेंडर होने से पहले `init` कॉलबैक के अंदर `tsparticles` (या आपके आवश्यक प्रीसेट) लोड किए गए हैं। +- **कैनवस दिखाई नहीं दे रहा** — सत्यापित करें कि पैरेंट कंटेनर में गैर-शून्य ऊँचाई है। `#tsparticles { height: 100vh; }` जैसा CSS नियम जोड़ें। +- **प्रदर्शन संबंधी समस्याएँ** — कम-अंत वाले उपकरणों पर `fpsLimit` कम करें, `particles.number.value` घटाएँ, या `detectRetina` अक्षम करें। +- **SSR (Nuxt)** — `` घटक केवल-क्लाइंट है। इसे `` में लपेटें या `client:only` डायरेक्टिव का उपयोग करें। diff --git a/websites/website/docs/hi/guides/webcomponents.md b/websites/website/docs/hi/guides/webcomponents.md new file mode 100644 index 00000000000..040f2cbaa66 --- /dev/null +++ b/websites/website/docs/hi/guides/webcomponents.md @@ -0,0 +1,359 @@ +# वेब कम्पोनेंट + +`@tsparticles/webcomponents` पैकेज के माध्यम से tsParticles का उपयोग मूल वेब कम्पोनेंट के साथ करें। इस दृष्टिकोण के लिए किसी फ्रेमवर्क की आवश्यकता नहीं है — बस सादा जावास्क्रिप्ट और कस्टम तत्व। + +## स्थापना + +### CDN के माध्यम से + +tsParticles कोर और वेब कम्पोनेंट बंडल शामिल करें: + +```html + + +``` + +### npm + बिल्ड के माध्यम से + +```bash +npm install @tsparticles/webcomponents tsparticles +``` + +फिर अपने जावास्क्रिप्ट बंडल में आयात करें: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; +``` + +## इंजन आरंभीकरण + +`` तत्व रेंडर होने से पहले, इंजन को आपकी आवश्यक सुविधाओं के साथ आरंभीकृत किया जाना चाहिए। वांछित प्लगइन लोड करने वाले कॉलबैक के साथ `initParticlesEngine` कॉल करें: + +```javascript +import { initParticlesEngine } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +> **`loadFull` क्यों?** यह सभी अंतर्निहित आकृतियों (वृत्त, वर्ग, बहुभुज, छवि, आदि), इंटरैक्शन (होवर, क्लिक), और अपडेटर (अपारदर्शिता, आकार, रंग, आदि) को पंजीकृत करता है। छोटे बंडल के लिए, `tsparticles-slim` का उपयोग करें या व्यक्तिगत प्लगइन चुनें। + +## कस्टम तत्व परिभाषित करना + +इंजन आरंभीकरण के बाद, `` कस्टम तत्व पंजीकृत करें: + +```javascript +import { defineParticlesElement } from "@tsparticles/webcomponents"; + +defineParticlesElement(); +``` + +यह ब्राउज़र के `CustomElementRegistry` के साथ `web-particles` टैग पंजीकृत करता है। इसे कई बार कॉल करना सुरक्षित है — डुप्लिकेट पंजीकरणों को अनदेखा किया जाता है। + +## मूल उपयोग + +एक बार जब `initParticlesEngine` और `defineParticlesElement` दोनों चल चुके हों, तो तत्व का सीधे HTML में उपयोग करें: + +```html + + + + + + tsParticles वेब कम्पोनेंट + + + + + + + +``` + +## कस्टम कॉन्फ़िगरेशन + +`` तत्व `options` प्रॉपर्टी (जावास्क्रिप्ट ऑब्जेक्ट) या `options` विशेषता में JSON के माध्यम से कॉन्फ़िगरेशन स्वीकार करता है। + +### जावास्क्रिप्ट प्रॉपर्टी के माध्यम से + +```javascript +const el = document.querySelector("web-particles"); +el.options = { + background: { color: "#000000" }, + fpsLimit: 60, + particles: { + color: { value: ["#ff0000", "#00ff00", "#0000ff"] }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { value: 60 }, + opacity: { value: 0.6 }, + shape: { type: ["circle", "square"] }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + repulse: { distance: 200 }, + push: { quantity: 4 }, + }, + }, +}; +``` + +### HTML विशेषता के माध्यम से (JSON) + +```html + +``` + +> `options` विशेषता का उपयोग करते समय, मान मान्य JSON होना चाहिए। जटिल कॉन्फ़िगरेशन के लिए प्रॉपर्टी असाइनमेंट पसंद किया जाता है। + +## डायनामिक निर्माण + +आप पूरी तरह से जावास्क्रिप्ट में `` तत्व बना सकते हैं और उन्हें किसी भी समय DOM में जोड़ सकते हैं: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +defineParticlesElement(); + +function createParticles(container, config) { + const el = document.createElement("web-particles"); + el.id = "dynamic-particles"; + el.style.position = "absolute"; + el.style.width = "100%"; + el.style.height = "100%"; + el.style.top = "0"; + el.style.left = "0"; + el.options = config; + container.appendChild(el); + return el; +} + +// उपयोग +const particles = createParticles(document.body, { + background: { color: "#1a1a2e" }, + particles: { + number: { value: 100 }, + links: { enable: true, color: "#e94560" }, + move: { enable: true, speed: 1 }, + }, +}); +``` + +## कस्टम तत्व का विस्तार + +आप अंतर्निहित कॉन्फ़िगरेशन के साथ अपना स्वयं का कस्टम तत्व बनाने के लिए `ParticlesElement` को उपवर्गित कर सकते हैं: + +```javascript +import { initParticlesEngine, ParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +class MyParticlesBackground extends ParticlesElement { + constructor() { + super(); + this.style.position = "fixed"; + this.style.top = "0"; + this.style.left = "0"; + this.style.width = "100%"; + this.style.height = "100%"; + this.style.zIndex = "-1"; + } + + connectedCallback() { + this.options = { + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true, speed: 2 }, + }, + }; + super.connectedCallback(); + } +} + +customElements.define("my-particles-bg", MyParticlesBackground); +``` + +उपयोग: + +```html + +``` + +## कंटेनर एक्सेस और नियंत्रण + +कस्टम तत्व अनिवार्य नियंत्रण के लिए tsParticles `Container` इंस्टेंस को उजागर करता है: + +```javascript +const el = document.querySelector("web-particles"); + +// कंटेनर तक पहुँच (connectedCallback के बाद उपलब्ध) +const container = el.container; +container?.pause(); +container?.play(); + +// नष्ट करें और साफ करें +el.dispose(); +``` + +## पूर्ण उदाहरण + +CDN स्क्रिप्ट के साथ वेब कम्पोनेंट मॉड्यूल का उपयोग करते हुए एक पूर्ण HTML पृष्ठ: + +```html + + + + + + tsParticles वेब कम्पोनेंट डेमो + + + +
+

tsParticles + वेब कम्पोनेंट

+

मूल कस्टम तत्व, किसी फ्रेमवर्क की आवश्यकता नहीं।

+
+ + + + + + +``` + +## API संदर्भ + +| निर्यात / प्रॉपर्टी | प्रकार | विवरण | +| ------------------------------- | ------------------------ | ----------------------------------------------------------- | +| `initParticlesEngine(callback)` | `function` | प्लगइन लोडर के साथ tsParticles इंजन आरंभीकृत करें | +| `defineParticlesElement()` | `function` | `` कस्टम तत्व पंजीकृत करें | +| `ParticlesElement` | `class` | आधार वर्ग जिसे आप कस्टम तत्वों के लिए विस्तारित कर सकते हैं | +| `element.options` | `ISourceOptions` | कण कॉन्फ़िगरेशन ऑब्जेक्ट प्राप्त/सेट करें | +| `element.container` | `Container \| undefined` | अंतर्निहित `Container` का केवल-पढ़ने योग्य संदर्भ | +| `element.dispose()` | `function` | कण इंस्टेंस नष्ट करें और संसाधन साफ करें | diff --git a/websites/website/docs/hi/guides/wordpress.md b/websites/website/docs/hi/guides/wordpress.md new file mode 100644 index 00000000000..5697d841531 --- /dev/null +++ b/websites/website/docs/hi/guides/wordpress.md @@ -0,0 +1,314 @@ +--- +title: वर्डप्रेस गाइड +description: प्लगइन, ब्लॉक, शॉर्टकोड और थीम एकीकरण का उपयोग करके tsParticles को वर्डप्रेस के साथ एकीकृत करने की पूर्ण मार्गदर्शिका। +--- + +# वर्डप्रेस गाइड + +## विषय सूची + +1. [स्थापना](#installation) +2. [प्लगइन सक्रियण](#plugin-activation) +3. [विजेट और ब्लॉक उपयोग](#widget-and-block-usage) +4. [शॉर्टकोड उपयोग](#shortcode-usage) +5. [PHP फ़िल्टर कॉन्फ़िगरेशन](#php-filter-configuration) +6. [फ़िल्टर के माध्यम से कस्टम कॉन्फ़िगरेशन](#custom-configuration-via-filter) +7. [थीम एकीकरण](#theme-integration) + +--- + +## स्थापना + +tsParticles वर्डप्रेस प्लगइन वर्डप्रेस प्लगइन निर्देशिका के माध्यम से उपलब्ध है। इसे सीधे अपने वर्डप्रेस एडमिन डैशबोर्ड से स्थापित करें। + +### वर्डप्रेस एडमिन से + +1. **प्लगइन → नया जोड़ें** पर जाएँ +2. "tsParticles" खोजें +3. tsParticles प्लगइन पर **अभी स्थापित करें** क्लिक करें +4. **सक्रिय करें** क्लिक करें + +### मैन्युअल स्थापना + +1. वर्डप्रेस प्लगइन निर्देशिका या [रिलीज़ पेज](https://github.com/tsparticles/wordpress/releases) से प्लगइन ZIP डाउनलोड करें +2. **प्लगइन → नया जोड़ें → प्लगइन अपलोड करें** पर जाएँ +3. ZIP फ़ाइल चुनें और **अभी स्थापित करें** क्लिक करें +4. **सक्रिय करें** क्लिक करें + +--- + +## प्लगइन सक्रियण + +सक्रिय होने के बाद, प्लगइन पंजीकृत करता है: + +- एक **गुटेनबर्ग ब्लॉक** जिसका नाम "tsParticles" है, जो ब्लॉक इन्सर्टर में उपलब्ध है +- एक **शॉर्टकोड** `[tsparticles]` क्लासिक एडिटर या कस्टम PHP टेम्पलेट में उपयोग के लिए +- एक **PHP फ़िल्टर** `tsparticles_options` डेवलपर्स के लिए प्रोग्रामेटिक रूप से कॉन्फ़िगरेशन इंजेक्ट करने हेतु +- फ्रंट-एंड संसाधन (जावास्क्रिप्ट और CSS) जो केवल तभी एनक्यू किए जाते हैं जब पृष्ठ पर ब्लॉक या शॉर्टकोड मौजूद हो + +सक्रियण के बाद, आप वर्डप्रेस एडमिन साइडबार में **सेटिंग → tsParticles** पर जाकर सत्यापित कर सकते हैं कि प्लगइन काम कर रहा है, जहाँ प्लगइन संस्करण के आधार पर एक मूल सेटिंग पृष्ठ उपलब्ध हो सकता है। + +--- + +## विजेट और ब्लॉक उपयोग + +tsParticles प्लगइन ब्लॉक एडिटर (वर्डप्रेस 5.0+) के लिए एक कस्टम गुटेनबर्ग ब्लॉक जोड़ता है। + +### ब्लॉक जोड़ना + +1. ब्लॉक एडिटर (गुटेनबर्ग) से किसी भी पोस्ट या पृष्ठ को संपादित करें +2. **+** (ब्लॉक जोड़ें) बटन क्लिक करें +3. "tsParticles" या "Particles" खोजें +4. इसे सम्मिलित करने के लिए **tsParticles** ब्लॉक क्लिक करें + +### ब्लॉक सेटिंग + +सम्मिलित करने के बाद, ब्लॉक इंस्पेक्टर पैनल (दाईं ओर) सेटिंग प्रदान करता है: + +- **कंटेनर आईडी** — कण कंटेनर के लिए एक अद्वितीय HTML आईडी (डिफ़ॉल्ट: `tsparticles`) +- **चौड़ाई / ऊँचाई** — स्पष्ट आयाम सेट करें या पूर्ण-स्क्रीन मोड का उपयोग करें +- **Z-इंडेक्स** — अन्य सामग्री के सापेक्ष लेयरिंग को नियंत्रित करता है +- **कॉन्फ़िगरेशन** — कण स्वरूप को पूरी तरह से अनुकूलित करने के लिए JSON ऑप्शन ऑब्जेक्ट पेस्ट करें + +थीम-साइडबार या विजेट क्षेत्रों के लिए जो ब्लॉक का समर्थन नहीं करते, इसके बजाय [शॉर्टकोड](#shortcode-usage) दृष्टिकोण का उपयोग करें। + +--- + +## शॉर्टकोड उपयोग + +अपनी साइट पर कहीं भी कण पृष्ठभूमि एम्बेड करने के लिए क्लासिक एडिटर, कस्टम HTML ब्लॉक, या सीधे PHP टेम्पलेट फ़ाइलों में `[tsparticles]` शॉर्टकोड का उपयोग करें। + +### मूल शॉर्टकोड + +``` +[tsparticles] +``` + +यह डिफ़ॉल्ट कण कॉन्फ़िगरेशन (गहरे रंग की पृष्ठभूमि पर सरल तैरते वृत्त) प्रस्तुत करता है। + +### विकल्पों के साथ शॉर्टकोड + +`options` विशेषता का उपयोग करके सीधे शॉर्टकोड में JSON कॉन्फ़िगरेशन पास करें: + +``` +[tsparticles options='{"particles":{"number":{"value":50},"color":{"value":"#ff0000"},"shape":{"type":"circle"},"opacity":{"value":0.5},"size":{"value":{"min":1,"max":3}},"move":{"enable":true,"speed":1,"outModes":{"default":"bounce"}}},"background":{"color":"#1a1a2e"}}'] +``` + +### PHP टेम्पलेट में शॉर्टकोड + +```php +// आपकी थीम के header.php या footer.php में +echo do_shortcode('[tsparticles]'); +``` + +या कस्टम विकल्पों के साथ: + +```php +$options = [ + 'particles' => [ + 'number' => ['value' => 80], + 'color' => ['value' => '#00d4ff'], + 'shape' => ['type' => 'circle'], + 'links' => [ + 'enable' => true, + 'distance' => 150, + 'color' => '#00d4ff', + 'opacity' => 0.3, + ], + 'move' => [ + 'enable' => true, + 'speed' => 1.5, + 'outModes' => ['default' => 'bounce'], + ], + ], + 'background' => ['color' => '#0d1117'], +]; + +echo do_shortcode('[tsparticles options=\'' . wp_json_encode($options) . '\']'); +``` + +--- + +## PHP फ़िल्टर कॉन्फ़िगरेशन + +प्लगइन एक `tsparticles_options` फ़िल्टर उजागर करता है जो आपको अपनी थीम की `functions.php` फ़ाइल या कस्टम प्लगइन से कण कॉन्फ़िगरेशन को ओवरराइड या विस्तारित करने देता है। यह डेवलपर्स के लिए अनुशंसित दृष्टिकोण है क्योंकि यह कॉन्फ़िगरेशन को PHP में रखता है और इनलाइन JSON से बचाता है। + +### मूल फ़िल्टर + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + $options['background'] = ['color' => '#0d1117']; + $options['particles']['number']['value'] = 100; + $options['particles']['color']['value'] = '#00d4ff'; + $options['particles']['shape']['type'] = 'circle'; + $options['particles']['opacity']['value'] = 0.6; + $options['particles']['size']['value'] = ['min' => 2, 'max' => 5]; + $options['particles']['links']['enable'] = true; + $options['particles']['links']['distance'] = 150; + $options['particles']['links']['color'] = '#00d4ff'; + $options['particles']['links']['opacity'] = 0.3; + $options['particles']['move']['enable'] = true; + $options['particles']['move']['speed'] = 1.5; + $options['particles']['move']['outModes']['default'] = 'bounce'; + return $options; +}); +``` + +यह फ़िल्टर शॉर्टकोड या ब्लॉक रेंडर होने से पहले चलता है, इसलिए पृष्ठ पर tsParticles का कोई भी इंस्टेंस अनुकूलित कॉन्फ़िगरेशन प्राप्त करता है। + +--- + +## फ़िल्टर के माध्यम से कस्टम कॉन्फ़िगरेशन + +यहाँ एक पूर्ण कस्टम कॉन्फ़िगरेशन है जो फ़िल्टर की पूरी क्षमता प्रदर्शित करता है — जिसमें इंटरैक्टिविटी, एकाधिक आकार प्रकार और थीम समर्थन शामिल हैं। + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + + // पूर्ण-स्क्रीन पृष्ठभूमि + $options['fullScreen'] = [ + 'enable' => true, + 'zIndex' => -1, + ]; + + $options['fpsLimit'] = 60; + + // कण सेटिंग + $options['particles'] = [ + 'number' => [ + 'value' => 60, + 'density' => ['enable' => true, 'width' => 800, 'height' => 800], + ], + 'color' => [ + 'value' => ['#ff6b6b', '#feca57', '#48dbfb', '#ff9ff3', '#54a0ff'], + ], + 'shape' => [ + 'type' => ['circle', 'triangle', 'polygon'], + 'options' => [ + 'polygon' => ['sides' => 6], + ], + ], + 'opacity' => [ + 'value' => ['min' => 0.4, 'max' => 0.8], + ], + 'size' => [ + 'value' => ['min' => 3, 'max' => 8], + ], + 'links' => [ + 'enable' => true, + 'distance' => 200, + 'color' => '#ffffff', + 'opacity' => 0.15, + 'width' => 1, + ], + 'move' => [ + 'enable' => true, + 'speed' => 2, + 'direction' => 'none', + 'random' => true, + 'straight' => false, + 'outModes' => ['default' => 'out'], + ], + ]; + + // इंटरैक्टिविटी + $options['interactivity'] = [ + 'events' => [ + 'onHover' => ['enable' => true, 'mode' => 'attract'], + 'onClick' => ['enable' => true, 'mode' => 'repulse'], + ], + 'modes' => [ + 'attract' => ['distance' => 200, 'duration' => 0.4, 'factor' => 1], + 'repulse' => ['distance' => 200, 'duration' => 0.4], + ], + ]; + + // पृष्ठभूमि + $options['background'] = [ + 'color' => '#0f0f23', + ]; + + // थीम समर्थन — लाइट मोड टॉगल + $options['themes'] = [ + [ + 'name' => 'light', + 'default' => ['value' => false], + 'options' => [ + 'background' => ['color' => '#f0f0f5'], + 'particles' => [ + 'color' => ['value' => ['#e74c3c', '#2ecc71', '#3498db', '#f1c40f']], + 'links' => ['color' => '#333333', 'opacity' => 0.2], + ], + ], + ], + ]; + + return $options; +}); +``` + +--- + +## थीम एकीकरण + +tsParticles को अपनी पूरी वर्डप्रेस थीम में एक स्थायी पृष्ठभूमि बनाने के लिए, अपनी थीम के `header.php` या `footer.php` में शॉर्टकोड या सीधा PHP कॉल जोड़ें। + +### हेडर पृष्ठभूमि + +```php + + +
+ +
+ +``` + +### पूर्ण-स्क्रीन पृष्ठभूमि शैलियाँ + +अपनी थीम के `style.css` में या `wp_add_inline_style` के माध्यम से निम्नलिखित CSS जोड़ें: + +```css +#tsparticles-background { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + z-index: -1; + pointer-events: none; +} + +/* सुनिश्चित करें कि सामग्री कणों के ऊपर दिखाई दे */ +.site-content { + position: relative; + z-index: 1; +} +``` + +### सशर्त लोडिंग + +केवल विशिष्ट पृष्ठों पर tsParticles लोड करने के लिए: + +```php +// functions.php में — केवल मुख्य पृष्ठ पर एनक्यू करें +add_action('wp', function () { + if (is_front_page()) { + add_filter('tsparticles_options', function (array $options): array { + $options['particles']['number']['value'] = 120; + $options['particles']['color']['value'] = '#ffffff'; + $options['particles']['move']['speed'] = 0.8; + $options['background']['color'] = '#1a1a2e'; + return $options; + }); + } +}); +``` + +इसे ब्लॉक या शॉर्टकोड प्लेसमेंट के साथ मिलाकर एक कुशल, पृष्ठ-विशिष्ट कण पृष्ठभूमि प्राप्त करें। + +--- + +अब आपके पास tsParticles को वर्डप्रेस साइट में एकीकृत करने के लिए आवश्यक सब कुछ है। चाहे आप ब्लॉक एडिटर, शॉर्टकोड, या पूर्ण PHP नियंत्रण पसंद करें, प्रत्येक दृष्टिकोण आपको न्यूनतम प्रयास के साथ एक अद्वितीय कण पृष्ठभूमि देता है। diff --git a/websites/website/docs/it/guide/bundles-all.md b/websites/website/docs/it/guide/bundles-all.md index d2c7ca3fbd8..4dd527ceae7 100644 --- a/websites/website/docs/it/guide/bundles-all.md +++ b/websites/website/docs/it/guide/bundles-all.md @@ -1,21 +1,42 @@ # Bundle: All -`@tsparticles/all` carica tutte le feature ufficiali, ideale per prototipare in fretta. +`@tsparticles/all` carica **tutto** il repository tsParticles: ogni forma, interazione, updater, effetto, percorso, easing, plugin ed esportazione. È il bundle più grande, pensato per prototipazione e demo. -## Quando scegliere All +## Funzionalità incluse -- Vuoi tutte le funzionalita subito disponibili. -- Stai esplorando opzioni rapidamente. -- La dimensione del bundle non e il vincolo principale. +Eredita tutto da `tsparticles` (full) più: + +**Tutte le forme:** arrow, cards, cog, heart, infinity, matrix, path, ribbon, rounded-polygon, rounded-rect, spiral, squircle + +**Tutte le interazioni:** cannon, light, particle, pop, particles-repulse + +**Tutti gli effetti:** bubble, filter, particles, shadow, trail + +**Tutti i path generator:** branches, brownian, curl-noise, curves, fractal-noise, grid, levy, perlin-noise, polygon, random, simplex-noise, spiral, svg, zig-zag + +**Tutti gli easing:** back, bounce, circ, cubic, elastic, expo, gaussian, linear, quad, quart, quint, sigmoid, sine, smoothstep + +**Tutti i plugin colore:** HEX, HSL, RGB, HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH + +**Tutti i plugin:** absorbers, background-mask, canvas-mask, emitters (con tutte le forme), easing (tutti), export-image, export-json, export-video, infection, manual-particles, motion, poisson-disc, polygon-mask, responsive, sounds, themes, trail, zoom + +**Tutti gli updater:** destroy, gradient, life, opacity, orbit, out-modes, paint, roll, rotate, size, tilt, twinkle, wobble + +## Quando usarlo + +- Prototipazione rapida per esplorare le possibilità +- Demo e showcase +- Ambienti di sviluppo dove la dimensione non è importante +- **Sconsigliato in produzione**: preferisci bundle più mirati ## Installazione +### Con npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/all ``` -## Esempio di setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadAll } from "@tsparticles/all"; @@ -25,20 +46,48 @@ await loadAll(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { number: { value: 100 }, + shape: { type: "heart" }, move: { enable: true, speed: 2 }, }, }, }); ``` -## Problemi comuni +### Con CDN (tag ` + + +``` + +## Differenza tra `tsparticles` e `@tsparticles/all` + +Vedi la tabella completa sulla [pagina bundles-full](/it/guide/bundles-full) per il confronto dettagliato. + +## Errori comuni -- Usarlo in produzione quando un bundle piu mirato sarebbe migliore. -- Chiamare `tsParticles.load(...)` prima di `loadAll(...)`. +- Usarlo in produzione — preferisci `@tsparticles/slim` o `tsparticles` per bundle più piccoli. +- Chiamare `tsParticles.load()` prima di `loadAll(tsParticles)`. -## Pagine correlate +## Vedi anche -- Panoramica: [`/guide/bundles`](/it/guide/bundles) -- Matrice installazione: [`/guide/installation`](/it/guide/installation) +- [Panoramica bundle](/it/guide/bundles) +- [Guida all'installazione](/it/guide/installation) diff --git a/websites/website/docs/it/guide/bundles-basic.md b/websites/website/docs/it/guide/bundles-basic.md index 3feaeb48940..cb670ff6745 100644 --- a/websites/website/docs/it/guide/bundles-basic.md +++ b/websites/website/docs/it/guide/bundles-basic.md @@ -1,21 +1,46 @@ # Bundle: Basic -`@tsparticles/basic` e pensato per setup molto leggeri con runtime minimo. +`@tsparticles/basic` è il bundle più leggero. Include solo l'essenziale: cerchi che si muovono con opacità e dimensione animabili. -## Quando scegliere Basic +## Funzionalità incluse -- La dimensione del bundle e la priorita principale. -- Ti servono solo effetti base. -- Non ti servono plugin avanzati. +**Forme:** cerchio + +**Updater (animazioni):** + +- paint (colore) +- opacity (opacità) +- out-modes (comportamento all'uscita dallo schermo) +- size (dimensione) + +**Plugin:** + +- move (movimento) +- blend (miscelazione colore) +- Colori HEX, HSL, RGB + +**Non include:** + +- Interazioni mouse/touch (click, hover, ecc.) +- Collegamenti tra particelle (links) +- Altre forme (quadrati, stelle, immagini, poligoni, ecc.) +- Emettitori, assorbitori, suoni +- Rotazione, vita, rollio, tilt, wobble + +## Quando usarlo + +- La dimensione del bundle è la priorità assoluta +- Servono solo pallini che si muovono +- Non servono interazioni o forme complesse ## Installazione +### Con npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/basic ``` -## Esempio di setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadBasic } from "@tsparticles/basic"; @@ -25,20 +50,48 @@ await loadBasic(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#ffffff" }, particles: { number: { value: 50 }, - move: { enable: true, speed: 1.5 }, + color: { value: ["#5bc0eb", "#fde74c", "#9bc53d"] }, + size: { + value: { min: 300, max: 400 }, + animation: { enable: true, speed: 100 }, + }, + move: { enable: true, speed: 10 }, }, }, }); ``` -## Problemi comuni +### Con CDN (tag ` + + +``` + +## Errori comuni -- Aspettarsi feature disponibili solo in plugin non inclusi. -- Chiamare `tsParticles.load(...)` prima di `loadBasic(...)`. +- Aspettarsi funzionalità che non sono incluse (es. `links`, interazioni mouse), che richiedono bundle superiori. +- Chiamare `tsParticles.load()` prima di `loadBasic(tsParticles)`: le forme e gli updater non sono ancora registrati. +- Installare solo `@tsparticles/engine` senza un bundle: l'engine da solo non disegna nulla. -## Pagine correlate +## Vedi anche -- Panoramica: [`/guide/bundles`](/it/guide/bundles) -- Matrice installazione: [`/guide/installation`](/it/guide/installation) +- [Panoramica bundle](/it/guide/bundles) +- [Guida all'installazione](/it/guide/installation) diff --git a/websites/website/docs/it/guide/bundles-confetti.md b/websites/website/docs/it/guide/bundles-confetti.md index 60f9b96655d..f95733c9b67 100644 --- a/websites/website/docs/it/guide/bundles-confetti.md +++ b/websites/website/docs/it/guide/bundles-confetti.md @@ -1,42 +1,83 @@ # Bundle: Confetti -`@tsparticles/confetti` espone un'API mirata per effetti coriandoli con setup minimo. +`@tsparticles/confetti` espone un'API semplificata per creare effetti coriandoli con una singola chiamata a funzione. Non richiede di interagire con `tsParticles` direttamente. -## Quando scegliere Confetti +## Funzionalità incluse -- Vuoi effetti celebrativi in una sola chiamata. -- Non ti serve cablare direttamente l'engine. -- Preferisci un'API compatta per eventi UI. +**Forme:** cerchio, cuore, carte (semi francesi: cuori, quadri, fiori, picche), emoji, immagini, poligono, quadrato, stella + +**Plugin interni:** emettitori, motion (rispetta le preferenze utente di riduzione animazioni) + +**Updater:** life, roll, rotate, tilt, wobble + +**API:** `confetti(options)` o `confetti(canvasId, options)` + +## Quando usarlo + +- Bottone "Congratulazioni!" o "Compleanno!" +- Effetto celebrazione rapido +- Non vuoi configurare l'engine manualmente ## Installazione +### Con npm/pnpm/yarn + ```bash pnpm add @tsparticles/confetti ``` -## Esempio di setup - ```ts import { confetti } from "@tsparticles/confetti"; +// Effetto base await confetti({ - count: 80, - spread: 60, + particleCount: 100, + spread: 70, + origin: { x: 0.5, y: 0.5 }, }); -await confetti("canvas-id", { - count: 50, +// Su un canvas specifico +await confetti("my-canvas-id", { + particleCount: 50, angle: 90, spread: 45, + colors: ["#ff0000", "#00ff00", "#0000ff"], }); ``` -## Problemi comuni +### Con CDN (tag ` + +``` + +### Parametri principali + +| Parametro | Tipo | Default | Descrizione | +| --------------- | -------- | ------------ | --------------------------------------------------- | +| `particleCount` | number | 50 | Numero di coriandoli | +| `spread` | number | 60 | Angolo di diffusione (gradi) | +| `angle` | number | 90 | Direzione (gradi, 90 = giù) | +| `startVelocity` | number | 30 | Velocità iniziale | +| `colors` | string[] | — | Colori dei coriandoli | +| `origin` | { x, y } | { 0.5, 0.5 } | Punto di origine (0-1) | +| `drift` | number | 0 | Deriva orizzontale | +| `shapes` | string[] | — | Forme: "circle", "heart", "square", "star", "cards" | + +## Errori comuni -- Pensare che `tsParticles` sia esportato da `@tsparticles/confetti`. -- Riutilizzare lo stesso id canvas senza volerlo. +- Pensare che `tsParticles` sia esportato da `@tsparticles/confetti` — non lo è. +- Riutilizzare lo stesso ID canvas senza volerlo. +- Chiamare `confetti` in loop senza gestire le performance: usa un intervallo ragionevole o ferma l'animazione quando non serve. -## Pagine correlate +## Vedi anche -- Panoramica: [`/guide/bundles`](/it/guide/bundles) -- Bundle playground: [`/playground/bundles`](/it/playground/bundles) +- [Panoramica bundle](/it/guide/bundles) +- [Bundle fireworks](/it/guide/bundles-fireworks) diff --git a/websites/website/docs/it/guide/bundles-fireworks.md b/websites/website/docs/it/guide/bundles-fireworks.md index 46d51be84f1..797f1fa2405 100644 --- a/websites/website/docs/it/guide/bundles-fireworks.md +++ b/websites/website/docs/it/guide/bundles-fireworks.md @@ -1,44 +1,81 @@ # Bundle: Fireworks -`@tsparticles/fireworks` espone un'API mirata per effetti fuochi d'artificio con setup minimo. +`@tsparticles/fireworks` espone un'API semplificata per creare effetti fuochi d'artificio con una singola chiamata. Supporta suoni, colori personalizzati e controllo dell'istanza (pause/play). -## Quando scegliere Fireworks +## Funzionalità incluse -- Vuoi animazioni fireworks in una sola chiamata. -- Non ti serve il wiring diretto dell'engine. -- Preferisci un'API compatta per momenti celebrativi. +**Forme:** linea, cerchio (da basic) + +**Plugin interni:** emettitori, emettitori-shape-square, blend (miscelazione), suoni (sounds) + +**Updater:** destroy, life, paint, rotate + +**API:** `fireworks(options)`, restituisce un'istanza controllabile + +## Quando usarlo + +- Effetto Capodanno o festa +- Celebration UI +- Non vuoi configurare l'engine manualmente ## Installazione +### Con npm/pnpm/yarn + ```bash pnpm add @tsparticles/fireworks ``` -## Esempio di setup - ```ts import { fireworks } from "@tsparticles/fireworks"; +// Effetto base const instance = await fireworks({ - colors: ["#ffffff", "#ff0000"], - sounds: false, + colors: ["#ffffff", "#ff0000", "#00ff00", "#0000ff"], + sounds: true, }); +// Controllo istanza instance?.pause(); instance?.play(); -await fireworks("canvas-id", { +// Su un canvas specifico +await fireworks("my-canvas", { rate: 3, speed: { min: 10, max: 25 }, + sounds: false, }); ``` -## Problemi comuni +### Con CDN (tag ` + +``` + +### Parametri principali + +| Parametro | Tipo | Default | Descrizione | +| ------------ | ------------ | ------- | ---------------------- | +| `colors` | string[] | — | Colori esplosione | +| `rate` | number | — | Fuochi al secondo | +| `speed` | { min, max } | — | Velocità particelle | +| `sounds` | boolean | true | Abilita effetti sonori | +| `gravity` | number | — | Gravità (default: 0) | +| `opacity` | number | — | Opacità (0-1) | +| `brightness` | { min, max } | — | Luminosità esplosione | + +## Errori comuni -- Pensare che `tsParticles` sia esportato da `@tsparticles/fireworks`. -- Chiamare `fireworks(...)` ripetutamente senza gestire l'istanza. +- Pensare che `tsParticles` sia esportato da `@tsparticles/fireworks` — non lo è. +- Chiamare `fireworks()` in loop senza gestire l'istanza: l'effetto è già continuo, non serve un intervallo. +- Non fermare l'istanza quando l'utente cambia pagina: chiama `instance?.pause()` o `instance?.stop()`. -## Pagine correlate +## Vedi anche -- Panoramica: [`/guide/bundles`](/it/guide/bundles) -- Bundle playground: [`/playground/bundles`](/it/playground/bundles) +- [Panoramica bundle](/it/guide/bundles) +- [Bundle confetti](/it/guide/bundles-confetti) diff --git a/websites/website/docs/it/guide/bundles-full.md b/websites/website/docs/it/guide/bundles-full.md index 55859103696..49adda067da 100644 --- a/websites/website/docs/it/guide/bundles-full.md +++ b/websites/website/docs/it/guide/bundles-full.md @@ -1,21 +1,48 @@ # Bundle: tsparticles (Full) -`tsparticles` e il bundle full e include un ampio set di funzionalita ufficiali con un solo loader. +`tsparticles` (npm: `tsparticles`, loader: `loadFull`) è il bundle ufficiale completo. Include tutte le funzionalità del bundle Slim più emettitori, assorbitori, forme di testo, animazioni avanzate (wobble, roll, tilt, twinkle, destroy). -## Quando scegliere tsparticles (Full) +## Funzionalità incluse -- Ti servono molte funzionalita ufficiali senza selezionare plugin manualmente. -- Vuoi una base completa pronta per la produzione prima delle ottimizzazioni. -- Preferisci il controllo engine tramite API `tsParticles`. +Eredita tutto da `@tsparticles/slim` più: + +**Forme aggiuntive:** text (testo con font personalizzati) + +**Interazioni esterne aggiuntive:** + +- drag (trascinamento particelle con mouse) +- trail (scia dietro il mouse) + +**Updater aggiuntivi:** + +- destroy (distruzione particelle con animazione) +- roll (rotolamento) +- tilt (inclinazione 3D) +- twinkle (scintillio intermittente) +- wobble (oscillazione) + +**Plugin:** + +- absorbers (assorbitori — buchi neri che risucchiano particelle) +- emitters (emettitori — fonti continue di particelle) +- emitters-shape-circle, emitters-shape-square (forme per emettitori) + +## Quando usarlo + +- Servono emettitori (particelle che spuntano continuamente) +- Servono assorbitori (particelle che vengono risucchiate) +- Servono forme di testo con font personalizzati +- Servono animazioni avanzate (wobble, tilt, roll, twinkle) +- Buon punto di arrivo prima di passare a plugin individuali ## Installazione +### Con npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine tsparticles ``` -## Esempio di setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadFull } from "tsparticles"; @@ -25,20 +52,65 @@ await loadFull(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { - number: { value: 100 }, - move: { enable: true, speed: 2 }, + number: { value: 50 }, + shape: { type: "text", options: { text: ["🔥", "✨", "⭐"] } }, + size: { value: 24 }, + move: { enable: true, speed: 1 }, + wobble: { enable: true, distance: 10 }, + }, + emitters: { + direction: "top", + rate: { quantity: 2, delay: 0.3 }, }, }, }); ``` -## Problemi comuni +### Con CDN (tag ` + + +``` + +## Differenza tra `tsparticles` e `@tsparticles/all` + +| Aspetto | `tsparticles` (full) | `@tsparticles/all` | +| ------------ | ------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| Dimensione | Contenuta | Molto grande | +| Forme | circle, square, star, polygon, line, image, emoji, text | Tutte le forme (cuore, carte, frecce, spirali, cog, rounded-rect, ecc.) | +| Interazioni | Slim + drag + trail | Tutte (cannon, light, pop, particle, repulse) | +| Path | Solo easing quad | 14 generatori di path | +| Effetti | Nessuno | 5 effetti (bubble, filter, shadow, ecc.) | +| Esportazioni | Nessuna | Image, JSON, Video | +| Plugin extra | absorbers, emitters | Tutti (sounds, themes, trail, zoom, polygon-mask, canvas-mask, background-mask, ecc.) | +| Easing | Quad | 15 easing | + +## Errori comuni -- Chiamare `tsParticles.load(...)` prima di `loadFull(...)`. -- Dare per scontato che sia lo stesso pacchetto di `@tsparticles/all` (sono bundle diversi). +- Confondere `tsparticles` con `@tsparticles/all` — non sono lo stesso pacchetto. +- Chiamare `tsParticles.load()` prima di `loadFull(tsParticles)`. +- Il package npm è `tsparticles` (non `@tsparticles/full`), il loader è `loadFull`. -## Pagine correlate +## Vedi anche -- Panoramica: [`/guide/bundles`](/it/guide/bundles) -- Matrice installazione: [`/guide/installation`](/it/guide/installation) +- [Panoramica bundle](/it/guide/bundles) +- [Guida all'installazione](/it/guide/installation) diff --git a/websites/website/docs/it/guide/bundles-particles.md b/websites/website/docs/it/guide/bundles-particles.md index 1fa0fdff87a..2a6144e5529 100644 --- a/websites/website/docs/it/guide/bundles-particles.md +++ b/websites/website/docs/it/guide/bundles-particles.md @@ -1,42 +1,98 @@ # Bundle: Particles -`@tsparticles/particles` espone un'API mirata per sfondi particellari semplici. +`@tsparticles/particles` espone un'API semplificata per creare sfondi particellari interattivi. È un'alternativa più ricca a `@tsparticles/basic` ma con API dedicata invece di configurare l'engine manualmente. -## Quando scegliere Particles +## Funzionalità incluse -- Vuoi un'API rapida per sfondi con particelle. -- Non ti serve configurare engine/plugin manualmente. -- Preferisci un'API compatta in stile app. +**Forme:** cerchio (da basic) + +**Plugin interni:** interactivity (collegamenti, collisioni) + +**Interazioni:** links (collegamenti tra particelle), collisions (collisioni) + +**API:** `particles(options)` o `particles(canvasId, options)` + +## Quando usarlo + +- Sfondo particellare per un sito web +- Sfondo con collegamenti tra particelle (stile "nodi") +- Non vuoi configurare l'engine manualmente ## Installazione +### Con npm/pnpm/yarn + ```bash pnpm add @tsparticles/particles ``` -## Esempio di setup - ```ts import { particles } from "@tsparticles/particles"; +// Sfondo con collegamenti await particles({ count: 120, links: true, - linksColor: "#0ff", + color: "#ffffff", + linksColor: "#00d8ff", + radius: 3, + speed: 2, + opacity: 0.8, }); -await particles("canvas-id", { +// Su un canvas specifico +await particles("my-canvas", { count: 80, shape: ["circle", "square"], + links: true, }); + +// Con colori personalizzati +await particles({ + count: 100, + color: ["#ff6b6b", "#4ecdc4", "#45b7d1"], + links: false, +}); +``` + +### Con CDN (tag ` + ``` -## Problemi comuni +### Parametri principali + +| Parametro | Tipo | Default | Descrizione | +| ------------ | ------------------ | ---------- | --------------------- | +| `count` | number | 50 | Numero particelle | +| `radius` | number | 3 | Raggio particelle | +| `speed` | number | 2 | Velocità movimento | +| `opacity` | number | 0.8 | Opacità (0-1) | +| `color` | string \| string[] | "#ffffff" | Colore/i particelle | +| `links` | boolean | false | Mostra collegamenti | +| `linksColor` | string | "#ffffff" | Colore collegamenti | +| `linksWidth` | number | 1 | Spessore collegamenti | +| `shape` | string[] | ["circle"] | Forme particelle | + +## Errori comuni -- Pensare che `tsParticles` sia esportato da `@tsparticles/particles`. -- Riutilizzare lo stesso id canvas senza volerlo. +- Pensare che `tsParticles` sia esportato da `@tsparticles/particles` — non lo è. +- Riutilizzare lo stesso ID canvas senza volerlo. +- Aspettarsi forme avanzate (stelle, poligoni) — il bundle particles è basato su basic e usa solo cerchi. -## Pagine correlate +## Vedi anche -- Panoramica: [`/guide/bundles`](/it/guide/bundles) -- Bundle playground: [`/playground/bundles`](/it/playground/bundles) +- [Panoramica bundle](/it/guide/bundles) +- [Guida per iniziare](/it/guide/getting-started) diff --git a/websites/website/docs/it/guide/bundles-slim.md b/websites/website/docs/it/guide/bundles-slim.md index 2dcadba9fe0..a931614950c 100644 --- a/websites/website/docs/it/guide/bundles-slim.md +++ b/websites/website/docs/it/guide/bundles-slim.md @@ -1,21 +1,61 @@ # Bundle: Slim -`@tsparticles/slim` e la scelta consigliata per la maggior parte dei progetti. +`@tsparticles/slim` è il bundle consigliato per la maggior parte dei progetti. Include tutto il necessario per creare animazioni di particelle moderne con interazioni mouse, forme multiple e collegamenti. -## Quando scegliere Slim +## Funzionalità incluse -- Vuoi un buon equilibrio tra peso e funzionalita. -- Usi direttamente l'API engine `tsParticles`. -- Ti servono forme/interazioni comuni senza caricare tutto. +Eredita tutto da `@tsparticles/basic` più: + +**Forme:** cerchio, quadrato, stella, poligono, linea, immagine, emoji + +**Interazioni esterne (mouse/touch):** + +- attract +- bounce +- bubble +- connect +- destroy +- grab +- parallax +- pause +- push +- remove +- repulse +- slow + +**Interazioni tra particelle:** + +- attract +- collisions (collisioni) +- links (collegamenti tra particelle) + +**Updater aggiuntivi:** + +- life (vita/ciclo) +- rotate (rotazione) + +**Plugin:** + +- interactivity (plugin per abilitare le interazioni) +- easing-quad (easing quadratico per animazioni) +- Colori HEX, HSL, RGB + +## Quando usarlo + +- Punto di partenza consigliato per la maggior parte dei progetti +- Servono forme multiple (cerchi, stelle, poligoni, immagini) +- Servono interazioni mouse (click, hover, bubble, repulse) +- Servono collegamenti tra particelle (links) +- Buon equilibrio tra dimensione del bundle e funzionalità ## Installazione +### Con npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/slim ``` -## Esempio di setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; @@ -25,21 +65,47 @@ await loadSlim(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#0b1020" }, particles: { number: { value: 80 }, + links: { enable: true, distance: 150 }, move: { enable: true, speed: 2 }, - links: { enable: true }, + shape: { type: ["circle", "star", "square"] }, }, }, }); ``` -## Problemi comuni +### Con CDN (tag ` + + +``` + +## Errori comuni -- Chiamare `tsParticles.load(...)` prima di `loadSlim(...)`. -- Mischiare versioni diverse tra engine e plugin. +- Chiamare `tsParticles.load()` prima di `loadSlim(tsParticles)`. +- Mescolare versioni diverse tra engine e bundle — mantienili allineati. +- Aspettarsi funzionalità che sono solo in bundle superiori (emettitori, assorbitori, testo, wobble): servono `tsparticles` (full) o plugin individuali. -## Pagine correlate +## Vedi anche -- Panoramica: [`/guide/bundles`](/it/guide/bundles) -- Matrice installazione: [`/guide/installation`](/it/guide/installation) +- [Panoramica bundle](/it/guide/bundles) +- [Guida all'installazione](/it/guide/installation) diff --git a/websites/website/docs/it/guide/bundles.md b/websites/website/docs/it/guide/bundles.md index a2fb2267515..cfae1d379a4 100644 --- a/websites/website/docs/it/guide/bundles.md +++ b/websites/website/docs/it/guide/bundles.md @@ -1,104 +1,186 @@ # Guida ai bundle -Questa pagina ti aiuta a scegliere il bundle `tsParticles` giusto e a configurarlo velocemente. - -## Confronto pacchetti - -| Pacchetto | Ideale per | Stile di setup | -| ------------------------ | ----------------------------------------------------------- | ---------------------------------------------- | -| `@tsparticles/basic` | Setup ultra leggeri | `tsParticles` + `await loadBasic(tsParticles)` | -| `@tsparticles/slim` | La maggior parte di siti/app | `tsParticles` + `await loadSlim(tsParticles)` | -| `tsparticles` | Set completo di funzionalita ufficiali con controllo engine | `tsParticles` + `await loadFull(tsParticles)` | -| `@tsparticles/all` | Tutte le funzionalita, prototipazione rapida | `tsParticles` + `await loadAll(tsParticles)` | -| `@tsparticles/confetti` | Effetti coriandoli con una chiamata | `await confetti(options)` | -| `@tsparticles/fireworks` | Effetti fuochi d'artificio con una chiamata | `await fireworks(options)` | -| `@tsparticles/particles` | API semplice per sfondo particellare | `await particles(options)` | -| `@tsparticles/ribbons` | Effetti ribbons con una chiamata | `await ribbons(options)` | - -## Guide per bundle - -- Basic: [`/guide/bundles-basic`](/it/guide/bundles-basic) -- Slim: [`/guide/bundles-slim`](/it/guide/bundles-slim) -- tsparticles (Full): [`/guide/bundles-full`](/it/guide/bundles-full) -- All: [`/guide/bundles-all`](/it/guide/bundles-all) -- Confetti: [`/guide/bundles-confetti`](/it/guide/bundles-confetti) -- Fireworks: [`/guide/bundles-fireworks`](/it/guide/bundles-fireworks) -- Particles: [`/guide/bundles-particles`](/it/guide/bundles-particles) -- Ribbons (demo + docs): [`/demos/recipes/ribbons`](/it/demos/recipes/ribbons) · - -## Installazione - -Installa il percorso pacchetto che corrisponde al tuo caso d'uso. - -```bash -pnpm add @tsparticles/engine @tsparticles/basic -pnpm add @tsparticles/engine @tsparticles/slim -pnpm add @tsparticles/engine tsparticles -pnpm add @tsparticles/engine @tsparticles/all -pnpm add @tsparticles/confetti -pnpm add @tsparticles/fireworks -pnpm add @tsparticles/particles -pnpm add @tsparticles/ribbons +tsParticles è modulare. Il pacchetto `@tsparticles/engine` contiene solo il motore base; per avere effetti visibili devi registrare **forme** (cosa disegnare), **updater** (come animare), **interazioni** (come reagire a mouse/touch) e **plugin** (funzionalità extra). Tutto questo avviene attraverso i **bundle**. + +## Categorie di bundle + +| Categoria | Bundle | API | +| --------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------- | +| Engine + loader | `@tsparticles/basic`, `@tsparticles/slim`, `tsparticles`, `@tsparticles/all` | `tsParticles.load({ id, options })` | +| API dedicata | `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles`, `@tsparticles/ribbons` | `confetti({...})`, `fireworks({...})`, ecc. | + +## Tabella comparativa completa + +Legenda: ● = incluso, ○ = non incluso + +| Funzionalità | basic | slim | full (`tsparticles`) | all | +| --------------------------------------------------------------------------------------------------- | ----- | ---- | -------------------- | ----------------- | +| **Forme (shape)** | | | | | +| Cerchio (circle) | ● | ● | ● | ● | +| Quadrato (square) | ○ | ● | ● | ● | +| Stella (star) | ○ | ● | ● | ● | +| Poligono (polygon) | ○ | ● | ● | ● | +| Linea (line) | ○ | ● | ● | ● | +| Immagine (image) | ○ | ● | ● | ● | +| Emoji | ○ | ● | ● | ● | +| Testo (text) | ○ | ○ | ● | ● | +| Carte (cards) | ○ | ○ | ○ | ● | +| Cuore (heart) | ○ | ○ | ○ | ● | +| Frecce (arrow) | ○ | ○ | ○ | ● | +| Rounded rect | ○ | ○ | ○ | ● | +| Rounded polygon | ○ | ○ | ○ | ● | +| Spirale (spiral) | ○ | ○ | ○ | ● | +| Squircle | ○ | ○ | ○ | ● | +| Cog (ingranaggio) | ○ | ○ | ○ | ● | +| Infinito (infinity) | ○ | ○ | ○ | ● | +| Matrice (matrix) | ○ | ○ | ○ | ● | +| Path | ○ | ○ | ○ | ● | +| Ribbon | ○ | ○ | ○ | ● | +| **Interazioni esterne (mouse/touch)** | | | | | +| Attract | ○ | ● | ● | ● | +| Bounce | ○ | ● | ● | ● | +| Bubble | ○ | ● | ● | ● | +| Connect | ○ | ● | ● | ● | +| Destroy | ○ | ● | ● | ● | +| Grab | ○ | ● | ● | ● | +| Parallax | ○ | ● | ● | ● | +| Pause | ○ | ● | ● | ● | +| Push | ○ | ● | ● | ● | +| Remove | ○ | ● | ● | ● | +| Repulse | ○ | ● | ● | ● | +| Slow | ○ | ● | ● | ● | +| Drag | ○ | ○ | ● | ● | +| Trail | ○ | ○ | ● | ● | +| Cannon | ○ | ○ | ○ | ● | +| Particle | ○ | ○ | ○ | ● | +| Pop | ○ | ○ | ○ | ● | +| Light | ○ | ○ | ○ | ● | +| **Interazioni tra particelle** | | | | | +| Links (collegamenti) | ○ | ● | ● | ● | +| Collisions (collisioni) | ○ | ● | ● | ● | +| Attract | ○ | ● | ● | ● | +| Repulse | ○ | ○ | ○ | ● | +| **Updater (animazioni)** | | | | | +| Opacità | ● | ● | ● | ● | +| Dimensione (size) | ● | ● | ● | ● | +| Out modes (uscita schermo) | ● | ● | ● | ● | +| Paint (colore) | ● | ● | ● | ● | +| Rotazione (rotate) | ○ | ● | ● | ● | +| Life (vita/ ciclo) | ○ | ● | ● | ● | +| Destroy (distruzione) | ○ | ○ | ● | ● | +| Roll (rotolamento) | ○ | ○ | ● | ● | +| Tilt (inclinazione) | ○ | ○ | ● | ● | +| Twinkle (scintillio) | ○ | ○ | ● | ● | +| Wobble (oscillazione) | ○ | ○ | ● | ● | +| Gradient | ○ | ○ | ○ | ● | +| Orbit | ○ | ○ | ○ | ● | +| **Plugin** | | | | | +| Move (movimento) | ● | ● | ● | ● | +| Blend (miscelazione) | ● | ● | ● | ● | +| Emettitori (emitters) | ○ | ○ | ● | ● | +| Assorbitori (absorbers) | ○ | ○ | ● | ● | +| Suoni (sounds) | ○ | ○ | ○ | ● | +| Motion (preferenze utente) | ○ | ○ | ○ | ● | +| Temi (themes) | ○ | ○ | ○ | ● | +| Polygon mask | ○ | ○ | ○ | ● | +| Canvas mask | ○ | ○ | ○ | ● | +| Background mask | ○ | ○ | ○ | ● | +| Export (immagine, json, video) | ○ | ○ | ○ | ● | +| Manual particles | ○ | ○ | ○ | ● | +| Responsive | ○ | ○ | ○ | ● | +| Trail | ○ | ○ | ○ | ● | +| Zoom | ○ | ○ | ○ | ● | +| Poisson disc | ○ | ○ | ○ | ● | +| **Percorsi (path)** | | | | | +| Qualsiasi path | ○ | ○ | ○ | ● (14 generatori) | +| **Effetti** | | | | | +| Bubble, Filter, Shadow, ecc. | ○ | ○ | ○ | ● (5 effetti) | +| **Easing** | | | | | +| Quad | ○ | ● | ● | ● | +| Back, Bounce, Circ, Cubic, Elastic, Expo, Gaussian, Linear, Quart, Quint, Sigmoid, Sine, Smoothstep | ○ | ○ | ○ | ● | +| **Plugin colore** | | | | | +| HEX, HSL, RGB | ● | ● | ● | ● | +| HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH | ○ | ○ | ○ | ● | + +### Bundle ad API dedicata + +| Funzionalità | confetti | fireworks | particles | ribbons | +| --------------- | ------------------------------------------------------------------ | ------------------------ | ------------------ | ------------------ | +| Forme | cerchio, cuore, carte, emoji, immagine, poligono, quadrato, stella | linea | (da basic) | ribbon | +| Interazioni | — | — | links + collisioni | — | +| Plugin speciali | emettitori, motion | emettitori, suoni, blend | — | emettitori, motion | +| API chiamata | `confetti(opts)` | `fireworks(opts)` | `particles(opts)` | `ribbons(opts)` | + +## Guida alla scelta + +```mermaid +flowchart TD + A[Devo iniziare in fretta?] -->|Sì| B[Uso un preset?] + A -->|No| C[Quale dimensione bundle?] + B -->|Sì| D["@tsparticles/configs + @tsparticles/slim"] + B -->|No| E["Coriandoli? → @tsparticles/confetti"] + B -->|No| F["Fuochi? → @tsparticles/fireworks"] + B -->|No| G["Sfondo particellare? → @tsparticles/particles"] + B -->|No| H["Nastri? → @tsparticles/ribbons"] + C -->|"Minima (solo cerchi)"| I["@tsparticles/basic"] + C -->|"Media (forme + interazioni)"| J["@tsparticles/slim"] + C -->|"Massima (tutte le funzionalità)"| K["tsparticles (loadFull)"] + C -->|"Tutto il repository"| L["@tsparticles/all"] ``` -Hai bisogno di link CDN e altre varianti dei package manager? - -- Vedi [`/guide/installation`](/it/guide/installation). - -## Esempi di setup - -### Bundle con engine + loader (`basic`, `slim`, `full`, `all`) - -```ts -import { tsParticles } from "@tsparticles/engine"; -import { loadSlim } from "@tsparticles/slim"; - -await loadSlim(tsParticles); - -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - number: { value: 80 }, - move: { enable: true, speed: 2 }, - }, - }, -}); +**Regole pratiche:** + +1. La maggior parte dei progetti parte da `@tsparticles/slim`. +2. Se la dimensione del bundle è critica e servono solo cerchi che si muovono: `@tsparticles/basic`. +3. Se servono emettitori, assorbitori, testo, wobble/tilt/roll: `tsparticles` con `loadFull`. +4. Per prototipazione rapida con tutte le funzionalità: `@tsparticles/all`. +5. Per effetti mirati (coriandoli, fuochi, particelle, nastri) con setup minimo: bundle ad API dedicata. + +## Installazione rapida + +| Bundle | Comando npm | Funzione loader | CDN URL | +| ------------------------ | ------------------------------------------------- | ------------------------ | -------------------------------------------------------------- | +| `@tsparticles/basic` | `pnpm add @tsparticles/engine @tsparticles/basic` | `loadBasic(tsParticles)` | `@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| `@tsparticles/slim` | `pnpm add @tsparticles/engine @tsparticles/slim` | `loadSlim(tsParticles)` | `@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| `tsparticles` (full) | `pnpm add @tsparticles/engine tsparticles` | `loadFull(tsParticles)` | `tsparticles@4/tsparticles.bundle.min.js` | +| `@tsparticles/all` | `pnpm add @tsparticles/engine @tsparticles/all` | `loadAll(tsParticles)` | `@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| `@tsparticles/confetti` | `pnpm add @tsparticles/confetti` | `confetti(opts)` | `@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| `@tsparticles/fireworks` | `pnpm add @tsparticles/fireworks` | `fireworks(opts)` | `@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| `@tsparticles/particles` | `pnpm add @tsparticles/particles` | `particles(opts)` | `@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| `@tsparticles/ribbons` | `pnpm add @tsparticles/ribbons` | `ribbons(opts)` | `@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | + +**Nota:** con i bundle basic/slim/full/all devi SEMPRE chiamare `load*` prima di `tsParticles.load()`. I file CDN espongono la funzione loader globalmente ma NON la chiamano automaticamente. I bundle confetti/fireworks/particles/ribbons invece hanno API autonoma: chiami direttamente `confetti()`, `fireworks()`, ecc. + +Esempio CDN per `@tsparticles/slim`: + +```html + + + ``` -Per gli altri preset, cambia solo import/funzione del loader: - -- `@tsparticles/basic` -> `loadBasic` -- `tsparticles` -> `loadFull` -- `@tsparticles/all` -> `loadAll` - -### API mirate (`confetti`, `fireworks`, `particles`, `ribbons`) +Esempio CDN per `@tsparticles/confetti`: -```ts -import { confetti } from "@tsparticles/confetti"; -import { fireworks } from "@tsparticles/fireworks"; -import { particles } from "@tsparticles/particles"; -import { ribbons } from "@tsparticles/ribbons"; - -await confetti({ count: 80, spread: 60 }); -await fireworks({ sounds: false }); -await particles({ count: 100, links: true }); -await ribbons({ count: 5, spread: 0 }); +```html + + ``` -Queste API sono ideali quando vuoi integrare in fretta senza collegare manualmente molti plugin engine. - -## Regole pratiche di scelta +Vedi anche la [guida all'installazione](/it/guide/installation) per CDN, npm, yarn, e dettagli sui file. -1. Inizia da `@tsparticles/slim` nella maggior parte dei progetti. -2. Usa `@tsparticles/basic` se la dimensione del bundle e la priorita assoluta e le funzionalita richieste sono semplici. -3. Usa `tsparticles` quando ti serve una base full con molte funzionalita e `loadFull`. -4. Usa `@tsparticles/all` per prototipazione o quando ti servono molte funzionalita subito. -5. Usa `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles` o `@tsparticles/ribbons` quando la UI richiede un effetto mirato con setup minimo. +Vedi anche la [guida all'installazione](/it/guide/installation) per CDN, npm, yarn, e dettagli sui file. ## Pagine correlate -- Bundle mirati nel playground: [`/playground/bundles`](/it/playground/bundles) -- Percorso per iniziare: [`/guide/getting-started`](/it/guide/getting-started) -- Matrice installazione: [`/guide/installation`](/it/guide/installation) -- Panoramica wrapper: [`/guide/wrappers`](/it/guide/wrappers) +- [Guida per iniziare](/it/guide/getting-started) +- [Guida all'installazione](/it/guide/installation) +- [Catalogo preset](/demos/presets) +- [Catalogo palette](/demos/palettes) +- [Catalogo forme](/demos/shapes) diff --git a/websites/website/docs/it/guide/color-formats.md b/websites/website/docs/it/guide/color-formats.md index 5dda97f1916..08743d1f122 100644 --- a/websites/website/docs/it/guide/color-formats.md +++ b/websites/website/docs/it/guide/color-formats.md @@ -1,6 +1,6 @@ # Formati di colore -tsParticles accetta più formati di colore tra opzioni come `background`, `particles.color` e impostazioni del plug-in. +tsParticles accetta più formati di colore tra opzioni come `background`, `particles.paint` e impostazioni del plug-in. ## Formati comuni diff --git a/websites/website/docs/it/guide/getting-started.md b/websites/website/docs/it/guide/getting-started.md index 9232b7071bb..9e304e62b3b 100644 --- a/websites/website/docs/it/guide/getting-started.md +++ b/websites/website/docs/it/guide/getting-started.md @@ -1,106 +1,198 @@ # Per iniziare -Questo percorso è la configurazione affidabile più rapida per `tsParticles` nel 2026. +tsParticles è una libreria JavaScript/TypeScript per creare animazioni di particelle, coriandoli, fuochi d'artificio e molto altro. Funziona in qualsiasi browser moderno ed è disponibile sia come pacchetto npm sia via CDN con tag ` + + + + +
+ + + +``` + +> **Nota**: anche con i bundle CDN devi chiamare `loadSlim(tsParticles)` (o `loadBasic` / `loadFull` / `loadAll`) prima di usare `tsParticles.load()`. I bundle CDN espongono la funzione loader globalmente ma non la chiamano automaticamente. + +Lo stesso schema vale per `@tsparticles/basic` → `loadBasic`, `tsparticles` → `loadFull`, `@tsparticles/all` → `loadAll`. + +### Percorso C — Bundle specializzati con API dedicata (coriandoli, fuochi, particelle) + +Alcuni bundle hanno una loro API semplificata, senza passare da `tsParticles.load()`: + +```html + + + + + + + + + +``` + +Stessa cosa per `fireworks()`, `particles()`, `ribbons()`. -- `@tsparticles/slim`: la maggior parte delle app dovrebbe iniziare qui. -- `@tsparticles/basic`: set di funzionalità più piccolo per configurazioni molto leggere. -- `@tsparticles/all`: tutto incluso, più semplice per una prototipazione veloce. +## Quale bundle scegliere? -Se hai bisogno di un'API mirata invece della configurazione diretta di `tsParticles`: +| Bundle | npm | Quando usarlo | +| ------------------------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `@tsparticles/basic` | `loadBasic(tsParticles)` | Minimo indispensabile: cerchi, movimento, opacità, dimensione. | +| `@tsparticles/slim` | `loadSlim(tsParticles)` | **Scelta consigliata per la maggior parte dei progetti.** Aggiunge interazioni (click/hover), collegamenti tra particelle, immagini, stelle, poligoni. | +| `tsparticles` | `loadFull(tsParticles)` | Set completo di funzionalità ufficiali: emettitori, assorbitori, forme testo, rollio, wobble, trail. | +| `@tsparticles/all` | `loadAll(tsParticles)` | **Tutto** il repository: ogni forma, interazione, effetto, easing, percorso, esportazione. Solo per prototipazione. | +| `@tsparticles/confetti` | `confetti(opzioni)` | Coriandoli in una chiamata. API dedicata. | +| `@tsparticles/fireworks` | `fireworks(opzioni)` | Fuochi d'artificio in una chiamata. API dedicata. | +| `@tsparticles/particles` | `particles(opzioni)` | Sfondo particellare semplificato. API dedicata. | +| `@tsparticles/ribbons` | `ribbons(opzioni)` | Effetto ribbon/nastri. API dedicata. | -- `@tsparticles/particles`: API di sfondo delle particelle semplificata -- `@tsparticles/confetti`: API coriandoli con una sola chiamata -- `@tsparticles/fireworks`: API fuochi d'artificio con una sola chiamata +Maggiori dettagli: [`/guide/bundles`](/it/guide/bundles). -## 5) Usa preimpostazioni/configurazioni quando hai bisogno di velocità +## Usare preset predefiniti -Se preferisci gli effetti predefiniti: +Il pacchetto `@tsparticles/configs` contiene decine di configurazioni pronte (assorbitori, bolle, neve, stelle, gravity, collisions, ecc.). ```bash -pnpm add @tsparticles/configs +pnpm add @tsparticles/engine @tsparticles/slim @tsparticles/configs +``` + +```ts +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import "@tsparticles/configs"; + +await loadSlim(tsParticles); + +// Carica un preset per nome +await tsParticles.load({ + id: "tsparticles", + options: { preset: "snow" }, +}); ``` -Quindi carica una configurazione per chiave, come l'[`demo/vite` app](https://github.com/tsparticles/tsparticles/blob/main/demo/vite/src/main.ts). +Con CDN: -Se preferisci configurazioni basate sul nome preimpostato, utilizza il catalogo ufficiale dei preimpostati in [`/demos/presets`](/it/demos/presets). +```html + + + + +``` -## Mappa della documentazione rapida +## Riferimenti rapidi -- Opzioni root: [`/options/`](/it/options/) -- Riferimento wrapper: [`/guide/wrappers`](/it/guide/wrappers) -- Catalogo preimpostazioni: [`/demos/presets`](/it/demos/presets) -- Catalogo tavolozze: [`/demos/palettes`](/it/demos/palettes) +- Documentazione delle opzioni: [`/options/`](/it/options/) +- Guida ai bundle: [`/guide/bundles`](/it/guide/bundles) +- Catalogo preset: [`/demos/presets`](/it/demos/presets) +- Catalogo palette: [`/demos/palettes`](/it/demos/palettes) - Catalogo forme: [`/demos/shapes`](/it/demos/shapes) -- Migrazione da particles.js: [`/migrations/particles-js`](/it/migrations/particles-js) +- Wrapper per framework: [`/guide/wrappers`](/it/guide/wrappers) - Formati colore: [`/guide/color-formats`](/it/guide/color-formats) - Ciclo di vita del contenitore: [`/guide/container-lifecycle`](/it/guide/container-lifecycle) - Plugin e personalizzazione: [`/guide/plugins-customization`](/it/guide/plugins-customization) ## Risoluzione dei problemi -- Schermata vuota: verificare che `#tsparticles` esista prima di chiamare `tsParticles.load`. -- Funzionalità mancante: probabilmente avrai bisogno di un altro plugin/pacchetto (forma, interazione, aggiornamento). -- Errori di digitazione sulle opzioni: mantieni i tuoi pacchetti allineati alla stessa versione maggiore/minore. +| Problema | Causa probabile | Soluzione | +| ------------------------------------------------------ | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | +| Schermo bianco, nessuna particella | `#tsparticles` non esiste nel DOM quando chiami `tsParticles.load()` | Verifica che il DIV sia presente prima dello script, oppure usa `DOMContentLoaded` | +| Schermo bianco, nessuna particella | Hai installato solo `@tsparticles/engine` | Devi installare anche un bundle (`@tsparticles/slim`) o dei plugin, perché l'engine da solo non ha forme da disegnare | +| Errore "loadBasic/loadSlim/loadFull is not a function" | Bundle non installato o import sbagliato | `pnpm add @tsparticles/slim` e importa `{ loadSlim }` | +| Le particelle non si muovono | `move.enable` non è impostato a `true` | Aggiungi `move: { enable: true, speed: 2 }` | +| Funzionalità mancante (es. collegamenti, collisioni) | Il bundle scelto non include quella funzionalità | Passa a un bundle più ricco (`@tsparticles/slim` o `tsparticles`) o installa il plugin specifico | +| Errori di tipo TypeScript | Versioni dei pacchetti non allineate | Mantieni engine e bundle sulla stessa versione maggiore/minore | diff --git a/websites/website/docs/it/guide/installation.md b/websites/website/docs/it/guide/installation.md index 801a07616ed..3b56e6185ff 100644 --- a/websites/website/docs/it/guide/installation.md +++ b/websites/website/docs/it/guide/installation.md @@ -1,109 +1,147 @@ # Installazione -Questa pagina rispecchia la matrice di installazione del README principale di `tsParticles`. - -Riferimento ufficiale: - ## Scegli il tuo percorso -- **Default rapido**: `@tsparticles/engine` + `@tsparticles/slim` -- **Runtime custom piu leggero**: `@tsparticles/engine` + solo plugin necessari -- **API focalizzate**: `@tsparticles/particles`, `@tsparticles/confetti`, `@tsparticles/fireworks` o `@tsparticles/ribbons` -- **Tutte le feature incluse**: `@tsparticles/all` - -## Hosting / CDN - -Usa uno di questi provider (oppure self-hosta i file buildati). +| Scenario | Comando | +| --------------------------- | ------------------------------------------------- | +| Inizio rapido (consigliato) | `pnpm add @tsparticles/engine @tsparticles/slim` | +| Minimo indispensabile | `pnpm add @tsparticles/engine @tsparticles/basic` | +| Set completo funzionalità | `pnpm add @tsparticles/engine tsparticles` | +| Tutto l'ecosistema | `pnpm add @tsparticles/engine @tsparticles/all` | +| Solo coriandoli | `pnpm add @tsparticles/confetti` | +| Solo fuochi d'artificio | `pnpm add @tsparticles/fireworks` | +| Sfondo particellare | `pnpm add @tsparticles/particles` | +| Effetto ribbon | `pnpm add @tsparticles/ribbons` | -### jsDelivr +> **Importante**: `@tsparticles/engine` da solo non disegna nulla. Devi sempre aggiungere un bundle (per caricare forme e animazioni) o dei plugin individuali. Vedi la [guida ai bundle](/it/guide/bundles). -- -- -- -- -- -- -- -- +## Con npm -### cdnjs +```bash +# engine + slim (consigliato per la maggior parte dei progetti) +npm install @tsparticles/engine @tsparticles/slim -- +# engine + basic (minimo) +npm install @tsparticles/engine @tsparticles/basic -### unpkg +# engine + full (tsparticles) +npm install @tsparticles/engine tsparticles -- -- -- -- -- -- -- -- +# engine + all (tutto) +npm install @tsparticles/engine @tsparticles/all -## Installazione con package manager +# Bundle ad API dedicata (non serve engine esplicito) +npm install @tsparticles/confetti +npm install @tsparticles/fireworks +npm install @tsparticles/particles +npm install @tsparticles/ribbons +``` -### npm +## Con yarn ```bash -npm install @tsparticles/engine +yarn add @tsparticles/engine @tsparticles/slim +# ... stesso schema degli altri bundle ``` -### yarn +## Con pnpm ```bash -yarn add @tsparticles/engine +pnpm add @tsparticles/engine @tsparticles/slim +# ... stesso schema degli altri bundle ``` -### pnpm +## Con CDN (tag ` + + + + +``` -- [`/guide/getting-started`](/it/guide/getting-started) -- [`/guide/wrappers`](/it/guide/wrappers) -- [`/demos/presets`](/it/demos/presets) -- [`/migrations/particles-js`](/it/migrations/particles-js) +Con i bundle ad API dedicata: -## Compatibilita legacy +```html + + +``` -Se stai migrando integrazioni particles.js legacy, usa il pacchetto di compatibilita: +## Pagine correlate -- npm: -- jsDelivr: +- [Per iniziare](/it/guide/getting-started) +- [Guida ai bundle](/it/guide/bundles) +- [Catalogo preset](/demos/presets) +- [Wrapper framework](/it/guide/wrappers) diff --git a/websites/website/docs/it/guides/angular.md b/websites/website/docs/it/guides/angular.md new file mode 100644 index 00000000000..680bacf5b2c --- /dev/null +++ b/websites/website/docs/it/guides/angular.md @@ -0,0 +1,631 @@ +--- +title: Integrazione Angular +description: Guida passo-passo per integrare tsParticles in applicazioni Angular usando @tsparticles/angular. +--- + +# Integrazione Angular + +Il pacchetto `@tsparticles/angular` fornisce componenti Angular, moduli e servizi per tsParticles. Questa guida copre l'approccio tradizionale con `NgModule` e i component standalone di Angular 17+. + +--- + +## Installazione + +```bash +npm install @tsparticles/angular @tsparticles/engine +``` + +Per l'insieme completo di funzionalità, installa il bundle completo: + +```bash +npm install tsparticles +``` + +Pacchetti preset opzionali: + +```bash +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +``` + +--- + +## Utilizzo Base (NgModule) + +### 1. Importa il Modulo + +```typescript +import { NgModule } from "@angular/core"; +import { BrowserModule } from "@angular/platform-browser"; +import { NgParticlesModule } from "@tsparticles/angular"; +import { AppComponent } from "./app.component"; + +@NgModule({ + declarations: [AppComponent], + imports: [BrowserModule, NgParticlesModule], + bootstrap: [AppComponent], +}) +export class AppModule {} +``` + +### 2. Inizializza il Motore + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d47a1", + }, + fpsLimit: 120, + particles: { + number: { + value: 80, + }, + color: { + value: "#ffffff", + }, + shape: { + type: "circle", + }, + opacity: { + value: 0.5, + }, + size: { + value: { min: 1, max: 5 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Contenitore particelle caricato", container); + } +} +``` + +### 3. Template + +```html + +``` + +--- + +## Dettagli Inizializzazione Motore + +Il metodo `NgParticlesService.init()` deve essere chiamato una sola volta, tipicamente in `AppComponent.ngOnInit()`. Riceve una callback dove caricare i plugin/preset necessari all'applicazione. + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesService } from "@tsparticles/angular"; +import type { Engine } from "@tsparticles/engine"; + +@Component({ ... }) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + // Carica solo ciò che serve per bundle più piccoli + await loadBasic(engine); // forme base + movimento + await loadEmittersPlugin(engine); // forme emettitore + }); + } +} +``` + +Funzioni di caricamento disponibili da `tsparticles`: + +| Funzione | Descrizione | +| ------------------- | ---------------------------------------------------------------- | +| `loadFull(engine)` | Tutte le funzionalità (bundle più grande) | +| `loadBasic(engine)` | Forme base (cerchio, quadrato, poligono, ecc.) | +| `loadSlim(engine)` | La maggior parte delle funzionalità senza plugin usati raramente | +| `loadAll(engine)` | Alias deprecato per `loadFull` | + +--- + +## Effetto Coriandoli + +```bash +npm install @tsparticles/preset-confetti +``` + +```typescript +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// Nella callback di NgParticlesService.init: +await loadConfettiPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "confetti", + background: { + color: "transparent", + }, +}; +``` + +Oppure usa il componente ``: + +```typescript +// app.module.ts +import { NgParticlesModule } from "@tsparticles/angular"; + +@NgModule({ + imports: [NgParticlesModule], +}) +export class AppModule {} +``` + +```html + +``` + +--- + +## Effetto Fuochi d'Artificio + +```bash +npm install @tsparticles/preset-fireworks +``` + +```typescript +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; + +// Nella callback di NgParticlesService.init: +await loadFireworksPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "fireworks", + background: { + color: "#000000", + }, +}; +``` + +Oppure usa il componente ``: + +```html + +``` + +> Evita di avviare automaticamente i fuochi d'artificio; collegali a un'azione dell'utente (clic, scroll) per prevenire un uso indesiderato di risorse. + +--- + +## Configurazione Personalizzata delle Particelle + +Configurazione personalizzata completa con interattività: + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-particles", + templateUrl: "./particles.component.html", +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d0d0d", + }, + fpsLimit: 60, + particles: { + number: { + value: 100, + density: { + enable: true, + }, + }, + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + shape: { + type: ["circle", "square", "triangle"], + }, + opacity: { + value: 0.8, + random: true, + anim: { + enable: true, + speed: 1, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + random: true, + anim: { + enable: true, + speed: 4, + size_min: 1, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.3, + width: 1, + triangles: { + enable: true, + color: "#ffffff", + opacity: 0.05, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { + enable: true, + rotateX: 600, + rotateY: 600, + }, + }, + life: { + duration: { + value: 5, + random: true, + }, + count: 0, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: { + enable: true, + }, + }, + modes: { + grab: { + distance: 200, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + detectRetina: true, + }; + + particlesLoaded(container: Container): void { + console.log("Container caricato", container); + } +} +``` + +```html + +``` + +--- + +## Eventi + +Il componente `ngx-particles` emette l'evento `particlesLoaded`: + +```typescript +import type { Container } from "@tsparticles/engine"; + +// Metodo del componente +onParticlesLoaded(container: Container): void { + // Accedi all'API del container + container.pause(); + container.play(); + container.destroy(); + container.exportImage().then((blob) => { /* ... */ }); +} +``` + +```html + +``` + +Il riferimento al container offre il controllo programmatico completo: pausa, ripristino, distruzione, esportazione e altro. + +--- + +## Sintassi Template e Rendering Condizionale + +Usa le direttive strutturali di Angular per attivare/disattivare il componente: + +```html + + + +``` + +```typescript +export class AppComponent { + showParticles = true; + // ... +} +``` + +Quando `*ngIf` vale `false`, il componente viene distrutto (inclusi canvas e tutte le istanze di particelle). Ricreandolo, tutto viene reinizializzato da capo. + +--- + +## Componenti Standalone (Angular 17+) + +In Angular 17+, puoi importare `NgParticlesModule` direttamente in un componente standalone: + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesModule, NgParticlesService } from "@tsparticles/angular"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +@Component({ + selector: "app-particles", + standalone: true, + imports: [NgParticlesModule], + template: ` + + `, +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 50 }, + color: { value: "#fff" }, + shape: { type: "circle" }, + move: { enable: true, speed: 2 }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Caricato", container); + } +} +``` + +Nessun wrapper `NgModule` necessario — basta importare `NgParticlesModule` nell'array `imports` del componente. + +--- + +## Esempio Completo di Componente + +### app.component.ts + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + title = "tsParticles Angular Demo"; + + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadSlim(engine); + }); + } + + particlesOptions: ISourceOptions = { + autoPlay: true, + background: { + color: "#1e1e2e", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMask: { + cover: { + color: "#1e1e2e", + }, + enable: false, + }, + fullScreen: { + enable: true, + zIndex: -1, + }, + detectRetina: true, + fpsLimit: 60, + particles: { + color: { + value: "#cdd6f4", + }, + links: { + color: "#cdd6f4", + distance: 150, + enable: true, + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1, + }, + number: { + value: 60, + }, + opacity: { + value: 0.6, + }, + size: { + value: { min: 1, max: 3 }, + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Particelle caricate", container); + } +} +``` + +### app.component.html + +```html +
+ + +
+

{{ title }}

+

Le particelle sono in esecuzione nello sfondo.

+
+
+``` + +### app.component.css + +```css +:host { + display: block; + width: 100%; + height: 100%; +} +``` + +--- + +## Riferimento API + +| Componente | Selettore | Descrizione | +| ------------------ | --------------- | ----------------------------------------- | +| Particelle | `ngx-particles` | Componente sistema particelle completo | +| Coriandoli | `ngx-confetti` | Effetto coriandoli preconfigurato | +| Fuochi d'Artificio | `ngx-fireworks` | Effetto fuochi d'artificio preconfigurato | + +### Input di `ngx-particles` + +| Input | Tipo | Default | Descrizione | +| --------- | ---------------- | --------------- | ------------------------- | +| `id` | `string` | `"tsparticles"` | ID dell'elemento canvas | +| `options` | `ISourceOptions` | `{}` | Configurazione particelle | +| `url` | `string` | — | URL config JSON remota | + +### Output di `ngx-particles` + +| Output | Payload | Descrizione | +| ----------------- | ----------- | ------------------------------------------ | +| `particlesLoaded` | `Container` | Emesso quando il container è inizializzato | + +--- + +## Risoluzione dei Problemi + +- **Canvas bianco/invisibile** — Assicurati che l'elemento padre abbia un'altezza definita (es. `height: 100vh`). Il canvas assume le dimensioni del contenitore. +- **`NgParticlesService.init()` chiamato più volte** — Chiamalo una sola volta, tipicamente in `AppComponent.ngOnInit()`. Chiamate successive sono sicure ma ridondanti. +- **Modulo non trovato** — Verifica che `@tsparticles/angular` sia elencato nelle dipendenze di `package.json` e di aver importato `NgParticlesModule`. +- **`NullInjectorError: No provider for NgParticlesService`** — Devi importare `NgParticlesModule` (o riesportarlo) nel modulo dove fornisci il componente. diff --git a/websites/website/docs/it/guides/astro.md b/websites/website/docs/it/guides/astro.md new file mode 100644 index 00000000000..0dfb2a83d85 --- /dev/null +++ b/websites/website/docs/it/guides/astro.md @@ -0,0 +1,384 @@ +# Integrazione Astro + +Usa tsParticles nel tuo sito Astro con il pacchetto ufficiale `@tsparticles/astro`. + +## Installazione + +Installa l'integrazione Astro e il core di tsParticles tramite il tuo gestore di pacchetti: + +```bash +npm install @tsparticles/astro tsparticles +``` + +```bash +pnpm add @tsparticles/astro tsparticles +``` + +```bash +yarn add @tsparticles/astro tsparticles +``` + +## Inizializzazione del Motore + +tsParticles usa un'architettura modulare. Prima di renderizzare le particelle, devi inizializzare il motore con le funzionalità che ti servono. Crea uno script client (es. `src/scripts/particles-init.ts`) o usa un ` +``` + +> La prop `id` viene passata al `
` contenitore del canvas sottostante. Usala per lo styling o l'accesso imperativo tramite `document.getElementById()`. + +## Supporto TypeScript + +L'integrazione include dichiarazioni TypeScript complete. Usa `ISourceOptions` da `@tsparticles/engine` per tipizzare la tua configurazione: + +```typescript +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { + value: 50, + density: { enable: true }, + }, + opacity: { value: 0.5 }, + shape: { type: "circle" }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + repulse: { distance: 200 }, + }, + }, +}; +``` + +## Configurazione Personalizzata + +Ecco una configurazione più elaborata che puoi inserire in qualsiasi pagina Astro: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + autoPlay: true, + background: { + color: "#0d47a1", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMode: { + enable: true, + zIndex: -1, + }, + fpsLimit: 120, + particles: { + color: { + value: "#ffffff", + animation: { + enable: true, + speed: 20, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + triangles: { + enable: true, + opacity: 0.1, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "out", + attract: { enable: false }, + }, + number: { + value: 80, + density: { + enable: true, + }, + }, + opacity: { + value: 0.5, + animation: { + enable: true, + speed: 1, + sync: false, + }, + }, + shape: { + type: "circle", + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 3, + sync: false, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: true, + }, + modes: { + grab: { + distance: 200, + links: { opacity: 0.5 }, + }, + push: { quantity: 4 }, + }, + }, + detectRetina: true, +}; +--- + + + + +``` + +## Usare i Preset + +Invece di creare una configurazione manualmente, carica un preset durante l'inizializzazione del motore e referenzialo nelle opzioni: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + preset: "stars", + background: { color: "#000000" }, +}; +--- + + + + +``` + +## Integrazione con Altri Framework + +Poiché Astro supporta framework UI come React, Vue, Svelte e Solid, puoi usare il componente tsParticles specifico per framework all'interno di file `.astro`: + +### React in Astro + +```astro +--- +import Particles from "@tsparticles/react"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +### Vue in Astro + +```astro +--- +import Particles from "@tsparticles/vue3"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +> La direttiva `client:load` dice ad Astro di idratare il componente immediatamente al caricamento della pagina. Usa `client:visible` per un caricamento differito. + +## Esempio di Pagina Completa + +Una pagina Astro completa con particelle come sfondo animato: + +```astro +--- +import Layout from "../layouts/Layout.astro"; +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + number: { value: 100 }, + color: { value: "#ffffff" }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + size: { + value: { min: 1, max: 4 }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, +}; +--- + + +
+

Benvenuto

+

Questa pagina ha uno sfondo con particelle alimentato da tsParticles.

+
+ +
+ + + + +``` + +## Props del Componente + +| Prop | Tipo | Default | Descrizione | +| -------------------- | ---------------- | ------------------------- | ---------------------------------------------- | +| `id` | `string` | `"tsparticles"` | ID dell'elemento DOM per il contenitore | +| `options` | `ISourceOptions` | `{}` | Oggetto di configurazione tsParticles completo | +| `url` | `string` | — | Carica configurazione da URL JSON remota | +| `particlesClassName` | `string` | `"tsparticles-canvas-el"` | Classe CSS per l'elemento canvas | +| `container` | `object` | — | Istanza `Container` preesistente (avanzato) | diff --git a/websites/website/docs/it/guides/ember.md b/websites/website/docs/it/guides/ember.md new file mode 100644 index 00000000000..e1026ef815a --- /dev/null +++ b/websites/website/docs/it/guides/ember.md @@ -0,0 +1,346 @@ +--- +title: Guida Ember +description: Guida completa per integrare tsParticles con applicazioni Ember.js. +--- + +# Guida Ember + +## Indice dei Contenuti + +1. [Installazione](#installazione) +2. [Inizializzazione del Motore](#inizializzazione-del-motore) +3. [Utilizzo Base](#utilizzo-base) +4. [Configurazione Personalizzata](#configurazione-personalizzata) +5. [Gestione Eventi](#gestione-eventi) +6. [Rendering Condizionale](#rendering-condizionale) +7. [Esempio TypeScript](#esempio-typescript) + +--- + +## Installazione + +Installa l'addon Ember e il motore tsParticles tramite ember-cli: + +```bash +ember install @tsparticles/ember +``` + +Questo installerà l'addon e la sua dipendenza peer `tsparticles`. Puoi opzionalmente aggiungere pacchetti preset: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Inizializzazione del Motore + +L'addon esporta un'utilità `initParticlesEngine` che chiami una volta a livello di applicazione. Riceve una callback asincrona dove caricare le funzionalità, i preset o le forme necessarie alla tua app. + +```typescript +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadFull } from "tsparticles"; + +// Chiama questa durante il bootstrap dell'applicazione +if (typeof window !== "undefined") { + void initParticlesEngine(async (engine) => { + await loadFull(engine); + }); +} +``` + +Le posizioni tipiche per questa chiamata sono l'hook `beforeModel` della route applicazione, il costruttore di un controller applicazione o un inizializzatore di istanza. Il singleton del motore viene inizializzato una volta e condiviso tra tutti i componenti `` della tua app. + +--- + +## Utilizzo Base + +Dopo aver inizializzato il motore, usa il componente `` in qualsiasi template. Passa la tua configurazione delle particelle tramite l'argomento `@options`. + +```hbs +{{! app/templates/application.hbs }} + + +``` + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, + }; +} +``` + +--- + +## Configurazione Personalizzata + +Costruisci una configurazione più ricca con interattività, forme multiple e densità reattiva. + +```typescript +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class IndexController extends Controller { + options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, + }; +} +``` + +```hbs + +``` + +--- + +## Gestione Eventi + +Il componente `` attiva un'azione `@particlesLoaded` quando il container ha terminato l'inizializzazione e il primo frame è stato renderizzato. Usala per accedere all'istanza `Container` per il controllo programmatico. + +```typescript +import Controller from "@ember/controller"; +import { action } from "@ember/object"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + /* ... */ + }; + + @action + loadedCallback(container: Container) { + console.log("Particelle caricate", container.id); + + // Esempio di controllo programmatico: + setTimeout(() => { + container.pause(); + console.log("Particelle in pausa dopo 5 secondi"); + }, 5000); + } +} +``` + +```hbs + +``` + +Puoi anche usare il pattern callback inline con un helper di template se preferisci non definire un'azione separata. + +--- + +## Rendering Condizionale + +Usa l'helper `{{if}}` di Ember insieme a una proprietà `@tracked` per controllare quando il componente `` viene renderizzato. È utile quando l'inizializzazione del motore è asincrona e vuoi evitare di renderizzare il componente prima che il motore sia pronto. + +```typescript +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked engineReady = false; + + options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { enable: true, speed: 1, outModes: { default: "bounce" } }, + }, + background: { color: "#1a1a2e" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } +} +``` + +```hbs +{{#if this.engineReady}} + +{{else}} +

Caricamento particelle...

+{{/if}} +``` + +Il decoratore `@tracked` garantisce che il template venga ri-renderizzato automaticamente una volta che la promise si risolve. + +--- + +## Esempio TypeScript + +Ecco un controller applicazione Ember completo e tipizzato che dimostra il pattern di integrazione completo con preset slim, interattività e gestione del ciclo di vita. + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked private engineReady = false; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } + + @action + private handleParticlesLoaded(container: Container): void { + this.container = container; + console.log("Particelle caricate nel container:", container.id); + } +} +``` + +```hbs +{{! app/templates/application.hbs }} + +{{#if this.engineReady}} +
+

tsParticles + Ember

+ +
+{{else}} +
+

Inizializzazione motore particelle...

+
+{{/if}} +``` + +--- + +Ora hai tutto il necessario per integrare tsParticles in un'applicazione Ember.js. Ogni esempio è autonomo e pronto per essere copiato nel tuo progetto. diff --git a/websites/website/docs/it/guides/index.md b/websites/website/docs/it/guides/index.md new file mode 100644 index 00000000000..57541d4e3ad --- /dev/null +++ b/websites/website/docs/it/guides/index.md @@ -0,0 +1,58 @@ +--- +title: Guide Passo-Passo +description: Esplora le guide specifiche per framework per integrare tsParticles nel tuo progetto. +--- + +# Guide Passo-Passo + +Benvenuto nella sezione guide di tsParticles. Che tu stia costruendo un sito statico Vanilla JS, un'applicazione a pagina singola in React o Vue, o un'applicazione full-stack con Next.js o Nuxt, questi tutorial passo-passo ti guideranno attraverso installazione, utilizzo base, configurazioni avanzate ed effetti interattivi. + +Ogni guida è autonoma e include esempi di codice copiabili per iniziare rapidamente. + +## Guide Disponibili + +| Framework / Wrapper | Package | Descrizione | +| --------------------------------- | ------------------------------------------ | ------------------------------------------------- | +| [Vanilla JS](./vanilla) | `tsparticles` (CDN o npm) | Integrazione DOM diretta con `tsParticles.load()` | +| [React](./react) | `@tsparticles/react` | Wrapper React ufficiale con hook e API componenti | +| [Vue 3](./vue3) | `@tsparticles/vue3` | Plugin Vue 3 ufficiale con composables | +| [Angular](./angular) | `@tsparticles/angular` | Componente e modulo Angular ufficiale | +| [Svelte](./svelte) | `@tsparticles/svelte` | Componente Svelte ufficiale | +| [Next.js](./nextjs) | `@tsparticles/react` (con Next.js) | Rendering lato server e import dinamici | +| [Nuxt](./nuxt) | `@tsparticles/vue3` (con Nuxt) | Integrazione SSR-safe come plugin Nuxt | +| [Solid](./solid) | `@tsparticles/solid` | Wrapper SolidJS ufficiale | +| [Preact](./preact) | `@tsparticles/preact` | Componente compatibile con Preact | +| [Lit](./lit) | `@tsparticles/lit` | Wrapper componente web Lit | +| [Qwik](./qwik) | `@tsparticles/qwik` | Integrazione ottimizzata per Qwik | +| [jQuery](./jquery) | `@tsparticles/jquery` | Plugin jQuery per progetti legacy | +| [Astro](./astro) | `@tsparticles/react` (o qualsiasi wrapper) | Architettura a isole con direttive client | +| [Web Components](./webcomponents) | `@tsparticles/webcomponents` | Integrazione API Custom Elements | +| [Stencil](./stencil) | `@tsparticles/stencil` | Wrapper componente Stencil | +| [Ember](./ember) | `@tsparticles/ember` | Addon Ember | +| [Riot](./riot) | `@tsparticles/riot` | Wrapper Riot.js | +| [Inferno](./inferno) | `@tsparticles/inferno` | Componente compatibile con Inferno | +| [WordPress](./wordpress) | Plugin + `tsparticles` | Integrazione editor a blocchi / shortcode | + +## Scegli la Tua Guida + +- [Vanilla JS (JavaScript puro)](./vanilla) +- [React](./react) +- [Vue 3](./vue3) +- [Angular](./angular) +- [Svelte](./svelte) +- [Next.js](./nextjs) +- [Nuxt](./nuxt) +- [Solid](./solid) +- [Preact](./preact) +- [Lit](./lit) +- [Qwik](./qwik) +- [jQuery](./jquery) +- [Astro](./astro) +- [Web Components](./webcomponents) +- [Stencil](./stencil) +- [Ember](./ember) +- [Riot](./riot) +- [Inferno](./inferno) +- [WordPress](./wordpress) + +Buon sviluppo! diff --git a/websites/website/docs/it/guides/inferno.md b/websites/website/docs/it/guides/inferno.md new file mode 100644 index 00000000000..de352898260 --- /dev/null +++ b/websites/website/docs/it/guides/inferno.md @@ -0,0 +1,373 @@ +--- +title: Guida Inferno +description: Guida completa per integrare tsParticles con applicazioni Inferno. +--- + +# Guida Inferno + +## Indice dei Contenuti + +1. [Installazione](#installazione) +2. [Utilizzo Base](#utilizzo-base) +3. [Inizializzazione del Motore](#inizializzazione-del-motore) +4. [Configurazione Personalizzata](#configurazione-personalizzata) +5. [Uso dei Preset](#uso-dei-preset) +6. [Pattern Componente](#pattern-componente) +7. [Esempio TypeScript](#esempio-typescript) + +--- + +## Installazione + +Installa il wrapper Inferno e il motore tsParticles tramite npm: + +```bash +npm install @tsparticles/inferno tsparticles +``` + +Installa opzionalmente il preset slim per un bundle più piccolo: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Utilizzo Base + +Il pacchetto `@tsparticles/inferno` esporta due elementi: `ParticlesProvider` e `Particles`. Avvolgi i tuoi componenti particella con `ParticlesProvider` che accetta una callback `init` per la configurazione del motore, poi usa `` per renderizzare il canvas delle particelle. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import { loadSlim } from "@tsparticles/slim"; + +const options = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +function App() { + return ( + { + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +`ParticlesProvider` deve essere un antenato di ogni componente ``. Inizializza il motore una volta e lo fornisce tramite contesto a tutti i figli. + +--- + +## Inizializzazione del Motore + +`ParticlesProvider` accetta una prop `init` che riceve l'istanza del motore. Qui è dove carichi le funzionalità, forme, preset o aggiornamenti necessari alla tua app. + +```tsx +// Leggero — particelle circolari, movimento base, collegamenti + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); +}}> + +// Insieme completo di funzionalità — tutte le forme, interazioni, effetti + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); +}}> + +// Preset-specifico — coriandoli, fuochi d'artificio, neve, stelle + { + const { loadConfettiPreset } = await import("@tsparticles/preset-confetti"); + await loadConfettiPreset(engine); +}}> +``` + +Usare `import()` dinamico all'interno della callback abilita il code splitting: i moduli preset o funzionalità vengono caricati solo quando il componente particella viene montato. + +--- + +## Configurazione Personalizzata + +Ecco una configurazione completa con interattività, tipi di forma multipli e uno sfondo sfumato scuro. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, +}; + +function App() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +--- + +## Uso dei Preset + +Il pacchetto `@tsparticles/configs` offre configurazioni predefinite che puoi passare direttamente alla prop `options`. Combinale con il corrispondente caricatore preset nella callback `init` di `ParticlesProvider`. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import configs from "@tsparticles/configs"; + +function App() { + return ( + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +Puoi sostituire `configs.confetti` con qualsiasi preset disponibile: `configs.basic`, `configs.fireworks`, `configs.snow`, `configs.stars`, ecc. + +--- + +## Pattern Componente + +Per applicazioni più grandi, struttura la logica delle particelle in un componente dedicato con una callback `particlesLoaded` per accedere all'istanza `Container`. + +```tsx +import { render, Component } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +class ParticlesBackground extends Component { + private container?: Container; + + handleParticlesLoaded(container?: Container) { + this.container = container; + console.log("Particelle caricate:", container?.id); + } + + render() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); + } +} + +function App() { + return ( +
+

tsParticles + Inferno

+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +## Esempio TypeScript + +Ecco un'applicazione Inferno completa e tipizzata con una configurazione di particelle reattiva e sfondo a schermo intero. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const particlesOptions: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +function handleInit(engine: Engine): Promise { + return import("@tsparticles/slim").then(({ loadSlim }) => loadSlim(engine)); +} + +function handleParticlesLoaded(container?: Container): void { + console.log("Container tsParticles pronto:", container?.id); +} + +function App() { + return ( + +
+

tsParticles + Inferno

+

Integrazione TypeScript completa

+
+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +Ora hai tutto il necessario per integrare tsParticles in un'applicazione Inferno. Ogni esempio è autonomo e pronto per essere copiato nel tuo progetto. diff --git a/websites/website/docs/it/guides/jquery.md b/websites/website/docs/it/guides/jquery.md new file mode 100644 index 00000000000..67ce2394ff3 --- /dev/null +++ b/websites/website/docs/it/guides/jquery.md @@ -0,0 +1,274 @@ +# Integrazione jQuery + +Integra tsParticles nei tuoi progetti basati su jQuery con il wrapper ufficiale del plugin jQuery. + +## Installazione + +### Via CDN + +Includi jQuery, tsParticles e il plugin jQuery tramite tag script: + +```html + + + +``` + +--- + +### Via npm + Build + +Installa i pacchetti richiesti: + +```bash +npm install jquery @tsparticles/jquery tsparticles +``` + +Importa nel tuo progetto: + +```javascript +import $ from "jquery"; +import "@tsparticles/jquery"; +``` + +## Inizializzazione del Motore + +Prima che le particelle possano essere renderizzate, il motore tsParticles deve essere inizializzato con le funzionalità necessarie. Questo avviene tramite `$.particles.init`: + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); +})(); +``` + +> **Perché è necessario?** tsParticles usa un'architettura modulare. `loadFull` registra tutte le forme, interazioni e aggiornamenti integrati. Puoi importare bundle più piccoli (es. `tsparticles-slim`) per ridurre la dimensione del bundle. + +## Utilizzo Base + +Una volta che il motore è inizializzato e il DOM è pronto, seleziona un elemento contenitore e chiama `.particles().load()`: + +```javascript +$(document).ready(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); + + $("#tsparticles") + .particles() + .load({ + background: { + color: "#0d47a1", + }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + }, + }); +}); +``` + +L'elemento contenitore deve esistere nel DOM: + +```html +
+``` + +## Configurazione Personalizzata + +Il metodo `.load()` accetta l'oggetto `ISourceOptions` completo. Ecco un esempio esaustivo: + +```javascript +$("#tsparticles") + .particles() + .load({ + background: { + color: "#000000", + }, + fpsLimit: 120, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + direction: "none", + enable: true, + outModes: "bounce", + speed: 4, + }, + number: { + density: { + enable: true, + }, + value: 60, + }, + opacity: { + value: 0.6, + }, + shape: { + type: ["circle", "square", "triangle"], + }, + size: { + value: { min: 2, max: 8 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + }, + interactivity: { + events: { + onClick: { + enable: true, + mode: "push", + }, + onHover: { + enable: true, + mode: "repulse", + }, + }, + modes: { + push: { + quantity: 4, + }, + repulse: { + distance: 200, + }, + }, + }, + }); +``` + +## Caricamento Preset + +Se hai installato un pacchetto preset (es. `tsparticles-preset-stars`), caricalo durante l'inizializzazione del motore e referenzialo nella configurazione: + +```bash +npm install tsparticles-preset-stars +``` + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadStarsPreset } = await import("tsparticles-preset-stars"); + await loadStarsPreset(engine); + }); + + $("#tsparticles") + .particles() + .load({ + preset: "stars", + background: { color: "#0d47a1" }, + }); +})(); +``` + +## Gestione Eventi e Controllo del Container + +`.particles()` restituisce un'istanza del plugin jQuery. Per accedere al `Container` tsParticles sottostante e chiamare metodi come `play()`, `pause()` o `destroy()`: + +```javascript +const $container = $("#tsparticles"); + +// Carica particelle +$container.particles().load({ + /* opzioni */ +}); + +// Play/pause dopo alcuni secondi +setTimeout(() => { + const container = $container.particles().getContainer(); + container?.pause(); +}, 5000); +``` + +## Esempio Completo + +Ecco una pagina HTML completa e autonoma che carica tsParticles via CDN e renderizza una scena di particelle con effetti interattivi: + +```html + + + + + + tsParticles + jQuery + + + +
+ + + + + + + +``` + +## Riferimento API + +| Metodo | Descrizione | +| ---------------------------------- | --------------------------------------------------------------- | +| `$.particles.init(fn)` | Inizializza il motore con una callback di caricamento | +| `$(el).particles()` | Crea un'istanza del plugin particelle sull'elemento | +| `$(el).particles().load(opts)` | Carica e avvia la configurazione delle particelle | +| `$(el).particles().destroy()` | Distrugge l'istanza delle particelle e pulisce | +| `$(el).particles().getContainer()` | Restituisce il `Container` sottostante per controllo imperativo | diff --git a/websites/website/docs/it/guides/lit.md b/websites/website/docs/it/guides/lit.md new file mode 100644 index 00000000000..25ba48accf7 --- /dev/null +++ b/websites/website/docs/it/guides/lit.md @@ -0,0 +1,301 @@ +--- +title: Lit +description: Integra tsParticles con Lit usando il wrapper ufficiale @tsparticles/lit per componenti web. +--- + +# Integrazione Lit + +Il pacchetto `@tsparticles/lit` fornisce un elemento personalizzato `` costruito con Lit, permettendoti di usare tsParticles in modo dichiarativo in qualsiasi progetto Lit o pagina HTML semplice. + +## Installazione + +```bash +npm install @tsparticles/lit tsparticles +``` + +Il pacchetto è completamente tipizzato e include i pattern di controller reattivi di Lit per aggiornare reattivamente le opzioni delle particelle. + +## Inizializzazione del Motore + +Chiama `initParticlesEngine` prima di registrare il componente `` o importarlo nella tua applicazione. Deve avvenire una sola volta. + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadFull } from "tsparticles"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +Per dimensioni del bundle ottimizzate, importa solo le funzionalità necessarie al tuo progetto: + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadBasic } from "@tsparticles/basic"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +void initParticlesEngine(async (engine) => { + await loadBasic(engine); + await loadConfettiPreset(engine); +}); +``` + +## Utilizzo Base + +Dopo che il motore è inizializzato, usa l'elemento `` in qualsiasi template Lit o file HTML: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private options = { + background: { + color: "#0d1117", + }, + particles: { + number: { value: 60 }, + color: { value: "#58a6ff" }, + links: { + enable: true, + color: "#58a6ff", + }, + move: { enable: true, speed: 2 }, + }, + }; + + render() { + return html` `; + } +} +``` + +La sintassi `.options` (con punto iniziale) è il property binding di Lit, che garantisce che l'oggetto sia passato per riferimento invece di essere serializzato come attributo. + +## Utilizzo in HTML Semplice + +Una volta che `@tsparticles/lit` è bundleizzato o caricato, l'elemento funziona anche in HTML semplice: + +```html + + + + + + + + + +``` + +Puoi passare un oggetto opzioni minimo come attributo JSON: + +```html + +``` + +## Configurazione Personalizzata + +Passa una configurazione tsParticles completa come proprietà Lit: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-particles") +class MyParticles extends LitElement { + @property({ type: Object }) + options: ISourceOptions = { + background: { + color: "#0d1117", + }, + fpsLimit: 120, + fullScreen: { + enable: true, + zIndex: -1, + }, + particles: { + color: { + value: ["#ff5733", "#33ff57", "#3357ff"], + }, + links: { + color: "#ffffff", + enable: true, + opacity: 0.3, + distance: 150, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + }, + number: { + value: 100, + density: { + enable: true, + }, + }, + opacity: { + value: 0.6, + animation: { + enable: true, + speed: 0.5, + minimumValue: 0.1, + }, + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 2, + minimumValue: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + }, + modes: { + grab: { + distance: 180, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + }; + + render() { + return html` `; + } +} +``` + +## Gestione Eventi + +Ascolta l'evento personalizzato `particles-loaded` emesso dall'elemento ``: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import type { Container } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private handleParticlesLoaded(e: CustomEvent) { + const container = e.detail; + console.log("Particelle caricate:", container); + container?.refresh(); + } + + render() { + return html` `; + } +} +``` + +## Esempio TypeScript + +Un elemento Lit completamente tipizzato con `initParticlesEngine`, opzioni reattive e gestione eventi: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import { initParticlesEngine } from "@tsparticles/lit"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import "@tsparticles/lit"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +@customElement("particles-background") +class ParticlesBackground extends LitElement { + @property({ type: Object }) + options: ISourceOptions = {}; + + @property({ type: Boolean, attribute: "fullscreen" }) + fullscreen = true; + + protected onParticlesLoaded(e: CustomEvent) { + console.log("Container pronto:", e.detail.id); + } + + render() { + return html` + + + `; + } +} +``` + +## Aggiornamenti Dinamici + +Poiché `` usa le proprietà reattive di Lit, cambiare la proprietà `options` aggiorna automaticamente le particelle: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("dynamic-particles") +class DynamicParticles extends LitElement { + @state() + private theme: "light" | "dark" = "dark"; + + private get options(): ISourceOptions { + return this.theme === "dark" + ? { + background: { color: "#0d1117" }, + particles: { color: { value: "#58a6ff" } }, + } + : { + background: { color: "#ffffff" }, + particles: { color: { value: "#0969da" } }, + }; + } + + private toggleTheme() { + this.theme = this.theme === "dark" ? "light" : "dark"; + } + + render() { + return html` + + + `; + } +} +``` + +Il componente osserva la proprietà `options` e chiama `refresh()` internamente ogni volta che cambia, aggiornando senza problemi la configurazione delle particelle in fase di esecuzione. diff --git a/websites/website/docs/it/guides/nextjs.md b/websites/website/docs/it/guides/nextjs.md new file mode 100644 index 00000000000..25375f2e336 --- /dev/null +++ b/websites/website/docs/it/guides/nextjs.md @@ -0,0 +1,492 @@ +--- +title: Integrazione Next.js +description: Guida passo-passo per integrare tsParticles in un'applicazione Next.js usando l'App Router. +--- + +# Integrazione Next.js + +Questa guida copre l'integrazione di tsParticles in un progetto Next.js usando l'**App Router** (Next.js 13+). Per il legacy Pages Router, consulta la sezione [Legacy Pages Router](#legacy-pages-router) in fondo. + +## Installazione + +Installa il wrapper `@tsparticles/react` e il motore `tsparticles` completo (o un bundle slim per build più piccole): + +```bash +npm install @tsparticles/react tsparticles +``` + +Se preferisci il bundle più piccolo `@tsparticles/slim`: + +```bash +npm install @tsparticles/react @tsparticles/slim +``` + +## Utilizzo Base (App Router) + +I componenti dell'App Router di Next.js sono lato server per impostazione predefinita. Poiché tsParticles richiede l'API `canvas` del browser, devi contrassegnare il componente con la direttiva `"use client"`. + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesBackground() { + const particlesLoaded = useCallback((container?: Container) => { + console.log("Particelle caricate", container); + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }), + [], + ); + + return ; +} +``` + +Crea questo file come `components/particles-background.tsx` e importalo in qualsiasi pagina o layout. Poiché il file inizia con `"use client"`, verrà renderizzato lato client — esattamente dove tsParticles deve essere. + +## Cambio Tema + +Combina tsParticles con i selettori di tema di Next.js derivando le opzioni dallo stato del tema corrente: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useMemo, useState, useCallback } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ThemeAwareParticles() { + const [theme, setTheme] = useState<"light" | "dark">("dark"); + + const toggleTheme = useCallback(() => { + setTheme((t) => (t === "dark" ? "light" : "dark")); + }, []); + + const particlesLoaded = useCallback((_container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { + color: theme === "dark" ? "#000000" : "#ffffff", + }, + particles: { + color: { value: theme === "dark" ? "#ffffff" : "#000000" }, + number: { value: 100 }, + links: { + enable: true, + color: theme === "dark" ? "#ffffff" : "#000000", + }, + move: { enable: true }, + }, + }), + [theme], + ); + + return ( + <> + + + + ); +} +``` + +L'oggetto `options` viene ricreato tramite `useMemo` ogni volta che `theme` cambia, quindi il canvas si aggiorna automaticamente. + +## Effetto Coriandoli + +Usa `@tsparticles/preset-confetti` per attivare coriandoli festivi su eventi come click sui pulsanti: + +```bash +npm install @tsparticles/preset-confetti +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Container, ISourceOptions, Engine } from "@tsparticles/engine"; + +export default function ConfettiButton() { + const [active, setActive] = useState(false); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadConfettiPreset(engine); + }, []); + + const particlesLoaded = useCallback( + async (container?: Container) => { + if (active && container) { + await container.play(); + } + }, + [active], + ); + + const options: ISourceOptions = useMemo( + () => ({ + preset: "confetti", + fullScreen: { zIndex: 1000 }, + }), + [], + ); + + const handleCelebrate = useCallback(() => { + setActive(true); + setTimeout(() => setActive(false), 5000); + }, []); + + return ( + <> + {active && } + + + ); +} +``` + +La callback `init` carica il preset coriandoli nel motore prima che le particelle vengano create. + +## Effetto Fuochi d'Artificio + +Allo stesso modo, il preset fuochi d'artificio crea uno spettacolo pirotecnico spettacolare: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; +import type { Container, Engine } from "@tsparticles/engine"; + +export default function FireworksBackground() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFireworksPreset(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options = useMemo( + () => ({ + preset: "fireworks" as const, + fullScreen: { zIndex: -1 }, + background: { + color: "#000", + }, + }), + [], + ); + + return ; +} +``` + +## Esempio TypeScript Completo con Riferimento al Container + +Accedi all'istanza `Container` per controllare l'animazione a livello di programmazione (play, pause, destroy, esporta immagine): + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +export default function ControllableParticles() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFull(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + fpsLimit: 120, + interactivity: { + events: { + onClick: { enable: true, mode: "push" }, + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + push: { quantity: 4 }, + repulse: { distance: 100 }, + }, + }, + particles: { + color: { value: "#ff0000" }, + links: { + enable: true, + color: "#ff0000", + distance: 150, + }, + move: { enable: true, speed: 2 }, + number: { value: 60 }, + size: { value: { min: 1, max: 5 } }, + }, + }), + [], + ); + + const handlePause = useCallback(() => { + containerRef.current?.pause(); + }, []); + + const handlePlay = useCallback(() => { + containerRef.current?.play(); + }, []); + + return ( +
+ +
+ + +
+
+ ); +} +``` + +Punti chiave: + +- `particlesInit` carica le funzionalità del motore (viene eseguito una sola volta per montaggio del componente). +- `particlesLoaded` viene attivato ogni volta che il container è completamente inizializzato. +- `containerRef` mantiene l'istanza `Container` per poter chiamare i suoi metodi in seguito. + +## Performance: useMemo e useCallback + +Avvolgi sempre le opzioni statiche o che cambiano raramente in `useMemo` e i gestori eventi in `useCallback` per prevenire ri-render non necessari del canvas: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function PerformanceExample() { + const [particlesCount, setParticlesCount] = useState(80); + + // Callback stabile — non viene mai ricreato a meno che le dipendenze non cambino + const particlesLoaded = useCallback((container?: Container) => { + console.log("Container pronto", container?.id); + }, []); + + // Oggetto opzioni stabile — previene la reinizializzazione del canvas + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: particlesCount }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [particlesCount], + ); + + return ( +
+ + +
+ ); +} +``` + +Senza queste ottimizzazioni, ogni re-render del genitore creerebbe un nuovo oggetto `options`, causando la ricreazione del canvas. + +## Integrazione nella Pagina + +Aggiungi uno sfondo di particelle a un layout di pagina senza influenzare il contenuto della pagina: + +```tsx +// app/layout.tsx (componente server) +import dynamic from "next/dynamic"; + +const ParticlesBackground = dynamic(() => import("@/components/particles-background"), { ssr: false }); + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + +
{children}
+ + + ); +} +``` + +Usa `dynamic()` con `ssr: false` per garantire che il componente non venga mai eseguito durante il rendering lato server. Il canvas delle particelle si posiziona dietro il contenuto principale tramite CSS `z-index`. + +## Istanze Multiple + +Puoi renderizzare diversi componenti `Particles` indipendenti sulla stessa pagina, ciascuno con la propria configurazione: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +function ParticlesGallery() { + const loaded = useCallback((c?: Container) => {}, []); + + const redOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#1a0000" }, + particles: { + color: { value: "#ff0000" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + const blueOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#00001a" }, + particles: { + color: { value: "#0000ff" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + return ( +
+ + +
+ ); +} +``` + +Ogni componente `Particles` crea un canvas indipendente con il proprio ciclo di animazione. Imposta `fullScreen: false` e assegna a ciascuno un'altezza fissa in modo che coesistano nel flusso del documento. + +## Legacy Pages Router + +Se stai usando il **Pages Router** di Next.js (directory `pages/`), l'approccio è simile ma senza la direttiva `"use client"`. Invece, puoi usare un import dinamico nel componente della pagina: + +```tsx +// pages/index.tsx +import dynamic from "next/dynamic"; +import type { NextPage } from "next"; + +const ParticlesComponent = dynamic(() => import("../components/particles-component"), { ssr: false }); + +const Home: NextPage = () => { + return ( +
+ +

Benvenuto

+
+ ); +}; + +export default Home; +``` + +Il componente stesso (`components/particles-component.tsx`) è un componente React semplice: + +```tsx +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesComponent() { + const particlesLoaded = useCallback((container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 80 }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [], + ); + + return ; +} +``` + +Nota che il Pages Router **non** richiede `"use client"` perché i componenti delle pagine sono già renderizzati lato client per impostazione predefinita. + +## Risoluzione dei Problemi + +| Sintomo | Causa | Rimedio | +| --------------------------- | ------------------------------------------------- | -------------------------------------------------------------------- | +| Pagina bianca | SSR di un modulo dipendente dal canvas | Usa `dynamic(..., { ssr: false })` o avvolgi in un componente client | +| Canvas non visibile | Il container ha altezza zero | Imposta `fullScreen: { zIndex: -1 }` o dagli dimensioni esplicite | +| Cambio opzioni non riflesso | Nuovo riferimento oggetto non creato | Usa `useMemo` con l'array di dipendenze corretto | +| Preset non funzionante | Preset non caricato prima dell'init del container | Chiama `loadXPreset(engine)` dentro la callback `init` | + +## Prossimi Passi + +- Esplora le [Demo Interattive](/demos/) per configurazioni già pronte. +- Leggi il [Riferimento Opzioni](/options/) per ogni parametro disponibile. +- Visita la pagina [Presets](/demos/presets) per altri preset predefiniti come neve, stelle e lucciole. diff --git a/websites/website/docs/it/guides/nuxt.md b/websites/website/docs/it/guides/nuxt.md new file mode 100644 index 00000000000..823e9bfbdde --- /dev/null +++ b/websites/website/docs/it/guides/nuxt.md @@ -0,0 +1,463 @@ +--- +title: Integrazione Nuxt +description: Guida passo-passo per integrare tsParticles in un'applicazione Nuxt 3 / Nuxt 4. +--- + +# Integrazione Nuxt + +Questa guida copre l'integrazione di tsParticles in un progetto **Nuxt 3** (e Nuxt 4) usando il wrapper ufficiale `@tsparticles/vue3`. Nuxt viene eseguito sia lato server che lato client, quindi devi proteggere i componenti delle particelle dall'SSR. + +## Installazione + +Installa il wrapper Vue 3 e il bundle del motore che preferisci: + +```bash +npm install @tsparticles/vue3 tsparticles +``` + +Per un bundle più piccolo, installa `@tsparticles/slim` invece di `tsparticles`: + +```bash +npm install @tsparticles/vue3 @tsparticles/slim +``` + +## Utilizzo Base + +Nuxt renderizza i componenti lato server per impostazione predefinita. Poiché tsParticles necessita dell'API `canvas` del browser, devi avvolgere il componente `` in un tag ``: + +```vue + + + + + +``` + +Il wrapper `` garantisce che il componente `` venga montato solo nel browser, prevenendo mismatch di idratazione. + +## Configurazione + +Usa il tipo `ISourceOptions` completo per una configurazione type-safe. Puoi definire le tue opzioni inline o importarle da un file di configurazione separato: + +```vue + +``` + +## Effetto Neve + +Crea un effetto nevoso invernale usando il preset snow: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +Poiché il preset viene caricato con `await` di primo livello in ` +``` + +Le modalità di interazione disponibili includono: `grab`, `bubble`, `connect`, `repulse`, `push`, `remove`, `attract` e `slow`. + +## Gestione Eventi + +Il componente `` emette diversi eventi del ciclo di vita: + +```vue + + + +``` + +| Evento | Payload | Descrizione | +| -------------------- | ----------- | --------------------------------------------------------------------------- | +| `@particles-init` | `Engine` | Viene attivato una volta quando il motore tsParticles si inizializza | +| `@particles-loaded` | `Container` | Viene attivato ogni volta che il container finisce di caricare o ricaricare | +| `@particles-destroy` | nessuno | Viene attivato quando il container viene distrutto | + +## Esempio TypeScript Completo + +Un componente completo e tipizzato con import espliciti e consapevolezza del ciclo di vita: + +```vue + + + + + +``` + +## Integrazione nella Pagina + +Aggiungi uno sfondo di particelle a una pagina Nuxt specifica posizionando il componente nel template della pagina: + +```vue + + + + + +``` + +Se vuoi le particelle su **ogni** pagina, aggiungi il componente a `layouts/default.vue` invece che a pagine singole. + +## Note su Nuxt 4 + +Nuxt 4 mantiene la retrocompatibilità con i pattern `` e ` +``` + +## Risoluzione dei Problemi + +| Sintomo | Causa | Rimedio | +| ------------------------------------------- | ------------------------------------------ | --------------------------------------------------------------------- | +| Schermata bianca / errore idratazione | `` renderizzato lato server | Avvolgi in `` | +| Il preset non ha effetto | Preset non caricato prima del montaggio | Chiama `loadXPreset()` con await di primo livello in ` + +``` + +Il motore si inizializza una volta e viene condiviso tra tutte le istanze `` nella tua app. + +--- + +## Utilizzo Base + +Dopo aver inizializzato il motore, usa il componente `` nel tuo template. Passa la configurazione come oggetto opzioni in formato JSON o come riferimento a una proprietà del tuo componente. + +```html + + + + + +``` + +--- + +## Rendering Condizionale + +Usa la direttiva `if={}` di Riot con una proprietà di stato per ritardare il rendering del componente particelle fino a quando il motore non ha terminato l'inizializzazione. Questo evita spostamenti del layout e garantisce che il componente riceva un motore pronto. + +```html + + + + + +``` + +Chiamare `this.update()` attiva un re-render cosicché il tag `` appaia una volta che la promise si risolve. + +--- + +## Uso dei Preset + +Il pacchetto `@tsparticles/configs` fornisce configurazioni predefinite per effetti comuni come coriandoli, fuochi d'artificio, neve e stelle. Usali direttamente come oggetto options. + +```html + + + + + +``` + +I preset disponibili includono `basic`, `confetti`, `fireworks`, `snow`, `stars` e altri. Ogni preset richiede che il corrispondente pacchetto preset sia caricato nella callback del motore. Ad esempio, `configs.fireworks` richiede `loadFireworksPreset`. + +--- + +## Configurazione Personalizzata + +Costruisci una configurazione personalizzata con interattività, forme multiple e opzioni di animazione avanzate. + +```html + + + + + +``` + +--- + +## Componente Completo + +Ecco un file `.riot` completo che unisce tutto: inizializzazione del motore in `onBeforeMount`, rendering condizionale con stato, una configurazione ricca con interattività e una callback `particlesLoaded` tramite il supporto integrato del componente per gli eventi caricati. + +```html + +
+

tsParticles + Riot.js

+ + {#if state.particlesInitialized} + + {:else} +

Caricamento motore particelle...

+ {/if} +
+ + + + +
+``` + +--- + +Ora hai tutto il necessario per integrare tsParticles in un'applicazione Riot.js. Ogni esempio è autonomo e pronto per essere copiato nel tuo progetto. diff --git a/websites/website/docs/it/guides/solid.md b/websites/website/docs/it/guides/solid.md new file mode 100644 index 00000000000..4da13793dc5 --- /dev/null +++ b/websites/website/docs/it/guides/solid.md @@ -0,0 +1,512 @@ +--- +title: Integrazione SolidJS +description: Guida passo-passo per integrare tsParticles in un'applicazione SolidJS usando il wrapper ufficiale @tsparticles/solid. +--- + +# Integrazione SolidJS + +Questa guida copre l'integrazione di tsParticles in un progetto **SolidJS** usando il wrapper ufficiale `@tsparticles/solid`. Il modello di reattività a grana fine di SolidJS funziona bene con tsParticles — i cambiamenti delle opzioni attivano aggiornamenti mirati del canvas senza reinizializzazione completa. + +## Installazione + +Installa il wrapper SolidJS e il bundle del motore che preferisci: + +```bash +npm install @tsparticles/solid tsparticles +``` + +Per un bundle più piccolo, usa `@tsparticles/slim` invece: + +```bash +npm install @tsparticles/solid @tsparticles/slim +``` + +## Utilizzo Base + +SolidJS viene eseguito interamente nel browser (nessun SSR), quindi non è necessario proteggersi dal rendering lato server. Tuttavia, il motore deve essere inizializzato in modo asincrono prima di renderizzare le particelle. + +Usa `initParticlesEngine` dentro `onMount` per caricare le funzionalità del motore, poi renderizza condizionalmente il componente `` con ``: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [initialized, setInitialized] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setInitialized(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +Il componente `` garantisce che l'elemento `` venga inserito nel DOM solo dopo che il motore è pronto. + +## Inizializzazione del Motore + +La funzione `initParticlesEngine` accetta una callback che riceve l'istanza `Engine`. Usa questa callback per registrare le funzionalità necessarie alla tua configurazione: + +```tsx +import { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import { loadSlim } from "@tsparticles/slim"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Engine } from "@tsparticles/engine"; + +// Minimo — solo forme base e movimenti +initParticlesEngine((engine: Engine) => loadSlim(engine)).then(() => { + console.log("Motore pronto (slim)"); +}); + +// Completo — ogni funzionalità inclusa +initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => { + console.log("Motore pronto (full)"); +}); + +// Solo preset — solo le funzionalità necessarie per un preset specifico +initParticlesEngine((engine: Engine) => loadConfettiPreset(engine)).then(() => { + console.log("Preset coriandoli caricato"); +}); +``` + +Chiama `initParticlesEngine` una volta nella tua app — tipicamente nell'`onMount` del componente radice. L'istanza del motore viene memorizzata nella cache, quindi le chiamate successive restituiscono immediatamente il risultato. + +## Rendering Condizionale + +Usa il controllo di flusso `` di SolidJS per differire il rendering fino a quando il motore non è inizializzato: + +```tsx +import { createSignal, Show, onMount } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import type { Engine } from "@tsparticles/engine"; +import type { Component } from "solid-js"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + Caricamento particelle...

}> + +
+ ); +}; +``` + +La prop `fallback` mostra un indicatore di caricamento mentre il motore si inizializza. + +## Uso dei Preset + +Usa `@tsparticles/configs` per configurazioni rapide e predefinite: + +```bash +npm install @tsparticles/configs +``` + +```tsx +import configs from "@tsparticles/configs"; +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + +
+ + +
+
+ ); +}; + +export default App; +``` + +Le configurazioni disponibili includono: `basic`, `bubbles`, `snow`, `stars`, `fireworks`, `confetti`, `links` e altre. + +## Particelle Interattive + +Aggiungi interazioni al click e al passaggio del mouse configurando la sezione `interactivity`: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 60 }, + links: { enable: true, distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 4 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +- **Modalità hover**: `grab`, `bubble`, `repulse`, `attract`, `slow`, `connect` +- **Modalità click**: `push`, `remove`, `repulse`, `bubble`, `attract`, `pause` + +## Configurazione Personalizzata + +Una configurazione personalizzata completa con forme multiple, palette di colori e impostazioni di movimento: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0a0a23" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { enable: true, rotateX: 600, rotateY: 1200 }, + }, + number: { + value: 40, + density: { enable: true }, + }, + opacity: { + value: { min: 0.3, max: 0.8 }, + animation: { + enable: true, + speed: 0.5, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + animation: { + enable: true, + speed: 2, + sync: false, + }, + }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.3, + width: 1, + }, + shape: { + type: ["circle", "square", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + twinkle: { + particles: { + enable: true, + frequency: 0.05, + opacity: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "bubble" }, + }, + modes: { + repulse: { distance: 120 }, + bubble: { distance: 200, size: 10, opacity: 0.8 }, + }, + }, + detectRetina: true, + }; + + return ( + + + + ); +}; + +export default App; +``` + +## Esempio TypeScript Completo + +Un componente tipizzato completo con riferimento al container, inizializzazione del motore e controlli manuali: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [container, setContainer] = createSignal(undefined); + const [paused, setPaused] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#1a1a2e" }, + particles: { + color: { value: "#e94560" }, + number: { value: 80 }, + links: { enable: true, color: "#e94560", distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 5 } }, + }, + }; + + const particlesLoaded = (c: Container) => { + setContainer(c); + }; + + const togglePause = () => { + const c = container(); + if (c) { + if (paused()) { + c.play(); + } else { + c.pause(); + } + setPaused(!paused()); + } + }; + + return ( + + + + + ); +}; + +export default App; +``` + +## Opzioni Dinamiche con Segnali + +Uno dei punti di forza di SolidJS è la reattività a grana fine — puoi usare i segnali per guidare le opzioni delle particelle e il canvas si aggiornerà in modo efficiente: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [color, setColor] = createSignal("#ff0000"); + const [particleCount, setParticleCount] = createSignal(60); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + // options è un oggetto normale — verrà letto in modo reattivo + // attraverso il tracciamento interno del componente Particles + const options = (): ISourceOptions => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#000" }, + particles: { + color: { value: color() }, + number: { value: particleCount() }, + links: { enable: true, color: color() }, + move: { enable: true }, + }, + }); + + return ( + + {}} /> +
+ + +
+
+ ); +}; + +export default App; +``` + +Poiché `options` è una funzione che accede ai segnali, ogni volta che `color()` o `particleCount()` cambia, il componente `` riceve un nuovo oggetto opzioni e applica solo le proprietà modificate al canvas esistente. + +## Preset con Sovrascritture Personalizzate + +Carica un preset, poi unisci sovrascritture personalizzate per un effetto su misura: + +```tsx +import { loadSnowPreset } from "@tsparticles/preset-snow"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadSnowPreset(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + preset: "snow", + fullScreen: { zIndex: -1 }, + background: { color: "#0d0d2b" }, + particles: { + // Sovrascrive il colore della neve in blu + color: { value: "#88ccff" }, + // Aumenta il numero di fiocchi + number: { value: 300 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +Il preset fornisce valori predefiniti per ogni opzione, e le tue sovrascritture vengono unite sopra — devi solo specificare le proprietà che vuoi cambiare. + +## Risoluzione dei Problemi + +| Sintomo | Causa | Rimedio | +| --------------------------- | ----------------------------------------- | ------------------------------------------------------------------------ | +| Elemento DOM vuoto | Motore non inizializzato prima del render | Avvolgi `` in `` | +| Nessuna particella visibile | Manca `move.enable` o `number.value` | Assicurati `particles.move.enable: true` e `particles.number.value > 0` | +| Canvas dietro il contenuto | Manca `zIndex` in fullScreen | Usa `fullScreen: { zIndex: -1 }` | +| Cambio opzioni non riflesso | Riferimento oggetto non cambiato | Avvolgi le opzioni in una funzione o store; evita oggetti statici | +| Motore non trovato | Manca import di `loadFull` o `loadSlim` | Installa `tsparticles` o `@tsparticles/slim` e chiama `loadFull(engine)` | + +## Prossimi Passi + +- Esplora il [Playground Configs](/playground/configs) per configurazioni già pronte. +- Leggi il [Riferimento Opzioni](/options/) per l'elenco completo dei parametri. +- Sfoglia il [codice sorgente SolidJS](https://github.com/tsparticles/solid) su GitHub per i dettagli interni del wrapper. diff --git a/websites/website/docs/it/guides/stencil.md b/websites/website/docs/it/guides/stencil.md new file mode 100644 index 00000000000..326e1531ffa --- /dev/null +++ b/websites/website/docs/it/guides/stencil.md @@ -0,0 +1,359 @@ +--- +title: Guida Stencil +description: Guida completa per integrare tsParticles con componenti Stencil. +--- + +# Guida Stencil + +## Indice dei Contenuti + +1. [Installazione](#installazione) +2. [Registrazione Elementi Personalizzati](#registrazione-elementi-personalizzati) +3. [Utilizzo Base](#utilizzo-base) +4. [Inizializzazione del Motore](#inizializzazione-del-motore) +5. [Configurazione Personalizzata](#configurazione-personalizzata) +6. [Ciclo di Vita del Componente](#ciclo-di-vita-del-componente) +7. [Esempio TypeScript](#esempio-typescript) + +--- + +## Installazione + +Installa il wrapper Stencil e il motore tsParticles tramite npm: + +```bash +npm install @tsparticles/stencil tsparticles +``` + +Installa opzionalmente un bundle preset per ridurre la configurazione manuale: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Registrazione Elementi Personalizzati + +Il pacchetto `@tsparticles/stencil` fornisce una funzione `defineCustomElements` che registra l'elemento personalizzato `` con il browser. Chiamala una volta prima di usare il componente in qualsiasi punto della tua app. + +```tsx +import { defineCustomElements } from "@tsparticles/stencil/loader"; + +// Registra l'elemento +defineCustomElements(); +``` + +Per progetti Stencil che usano lazy-loading, chiamala dentro `componentWillLoad` o nel componente radice della tua app per garantire che l'elemento sia disponibile prima del rendering. + +--- + +## Utilizzo Base + +Una volta che l'elemento personalizzato è registrato, puoi usare `` nel tuo JSX con una prop `options` e una callback `init` per caricare le funzionalità del motore necessarie. + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +@Component({ tag: "my-particles" }) +export class MyParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## Inizializzazione del Motore + +La prop `init` riceve l'istanza del motore e ti permette di caricare le funzionalità necessarie. Questo è il punto consigliato per chiamare `loadSlim`, `loadFull` o plugin di aggiornamento/interazione individuali. + +```tsx +import { loadSlim } from "@tsparticles/slim"; +import { loadFull } from "tsparticles"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// Opzione A: leggero (cerchi, movimento base, collegamenti) +init={async engine => { await loadSlim(engine); }} + +// Opzione B: insieme completo di funzionalità (tutte le forme, effetti, preset) +init={async engine => { await loadFull(engine); }} + +// Opzione C: preset (coriandoli, fuochi d'artificio, neve, stelle) +init={async engine => { await loadConfettiPreset(engine); }} +``` + +L'istanza del motore è anche accessibile dopo l'inizializzazione tramite l'attributo `container-id`, permettendoti di controllare programmaticamente il sistema di particelle in seguito se necessario. + +--- + +## Configurazione Personalizzata + +Ecco una configurazione completa con interattività, tipi di forma multipli e modalità hover/click. + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const fullOptions: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { + color: "#0f0f23", + }, +}; + +@Component({ tag: "app-particles" }) +export class AppParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## Ciclo di Vita del Componente + +In Stencil, l'hook del ciclo di vita consigliato per la configurazione una tantum è `componentWillLoad`. Usalo per registrare elementi personalizzati e gestire lo stato di inizializzazione in modo che il componente `` venga renderizzato solo quando il motore è pronto. + +```tsx +import { Component, h, State } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ tag: "app-root" }) +export class AppRoot { + @State() private engineReady = false; + + private options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { + enable: true, + speed: 1, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#1a1a2e" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.engineReady = true; + } + + render() { + return ( +
+

tsParticles + Stencil

+ {this.engineReady && ( + { + await loadSlim(engine); + }} + /> + )} +
+ ); + } +} +``` + +Usare `@State()` garantisce che il componente venga ri-renderizzato quando il motore diventa pronto, e il render condizionale impedisce che il container delle particelle venga montato prima che l'elemento personalizzato sia definito. + +--- + +## Esempio TypeScript + +Ecco un componente applicazione Stencil completo e tipizzato che integra tsParticles con il preset slim, interattività hover e un tema scuro personalizzato. + +```tsx +import { Component, h, State, Prop } from "@stencil/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ + tag: "app-home", + styleUrl: "app-home.css", + shadow: true, +}) +export class AppHome { + @State() private initialized = false; + + @Prop() readonly title: string = "Benvenuto"; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.initialized = true; + } + + private handleInit = async (engine: Engine): Promise => { + await loadSlim(engine); + }; + + private handleLoaded = async (container?: Container): Promise => { + this.container = container; + console.log("Container particelle caricato:", container?.id); + }; + + render() { + return ( +
+

{this.title}

+

Realizzato con tsParticles e Stencil

+ + {this.initialized && ( + + )} +
+ ); + } +} +``` + +L'evento `particlesLoaded` viene attivato una volta che il primo frame è renderizzato, dandoti accesso all'istanza `Container` per il controllo programmatico (play, pause, stop, cambio tema). + +--- + +Ora hai tutto il necessario per integrare tsParticles in un'applicazione Stencil. Ogni esempio è autonomo e pronto per essere copiato nel tuo progetto. diff --git a/websites/website/docs/it/guides/svelte.md b/websites/website/docs/it/guides/svelte.md new file mode 100644 index 00000000000..39c1f9d28aa --- /dev/null +++ b/websites/website/docs/it/guides/svelte.md @@ -0,0 +1,580 @@ +--- +title: Integrazione Svelte +description: Guida passo-passo per integrare tsParticles in applicazioni Svelte e SvelteKit usando @tsparticles/svelte. +--- + +# Integrazione Svelte + +Il pacchetto `@tsparticles/svelte` fornisce un componente Svelte nativo per tsParticles. Questa guida copre Svelte (con Vite) e SvelteKit, incluse opzioni reattive, gestione eventi e istanze multiple. + +--- + +## Installazione + +```bash +npm install @tsparticles/svelte @tsparticles/engine +``` + +Per il bundle completo o preset: + +```bash +npm install tsparticles +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +``` + +--- + +## Utilizzo Base + +```svelte + + + +``` + +--- + +## Inizializzazione del Motore + +Passa un gestore di eventi `on:init` per caricare i plugin e i preset necessari alla tua app: + +```svelte + + + +``` + +In alternativa, usa l'utilità `initParticlesEngine` prima del montaggio: + +```svelte + + +{#if ready} + +{/if} +``` + +--- + +## Effetto Neve + +```bash +npm install @tsparticles/preset-snow +``` + +```svelte + + + +``` + +Personalizza il comportamento del preset unendo opzioni aggiuntive: + +```svelte + +``` + +--- + +## Effetto Stelle + +```bash +npm install @tsparticles/preset-stars +``` + +```svelte + + + +``` + +--- + +## Particelle Interattive + +Aggiungi interattività al passaggio del mouse e al click: + +```svelte + + + +``` + +--- + +## Gestione Eventi + +```svelte + + +
+ + + +
+ + +``` + +| Evento | Dettaglio | Viene attivato | +| -------------------- | ----------- | -------------------------------------------- | +| `on:init` | `Engine` | Dopo che il motore è inizializzato | +| `on:particlesLoaded` | `Container` | Dopo che il container è completamente pronto | + +--- + +## Esempio TypeScript + +Componente tipizzato completo: + +```svelte + + + +``` + +--- + +## Opzioni Dinamiche + +Le opzioni reattive aggiornano le particelle senza ricreare l'istanza: + +```svelte + + +
+ +
+ + +``` + +La dichiarazione reattiva `$:` ricalcola `options` ogni volta che `color` cambia, e il componente `Particles` recepisce automaticamente la nuova configurazione. + +--- + +## Istanze Multiple + +Renderizza diversi sistemi di particelle indipendenti sulla stessa pagina: + +```svelte + + +
+
+ +
+
+ +
+
+``` + +Ogni componente `` ha il proprio `id`, canvas e contesto del motore. + +--- + +## Utilizzo con SvelteKit + +In SvelteKit, il canvas richiede l'ambiente browser. Disabilita SSR per il componente: + +```svelte + + +{#if Component} + +{/if} +``` + +Oppure avvolgi l'import in un componente solo client. Per SvelteKit 2+, puoi anche usare le esclusioni SSR di `vite-plugin-svelte`. + +--- + +## Riferimento API + +| Prop | Tipo | Default | Descrizione | +| --------- | ---------------- | --------------- | -------------------------------------- | +| `id` | `string` | `"tsparticles"` | ID dell'elemento canvas | +| `options` | `ISourceOptions` | `{}` | Oggetto di configurazione particelle | +| `url` | `string` | — | URL per una configurazione JSON remota | + +| Evento | Dettaglio | Descrizione | +| -------------------- | ----------- | ------------------------------------------------------------------------- | +| `on:init` | `Engine` | Viene attivato quando il motore è inizializzato (usa per caricare plugin) | +| `on:particlesLoaded` | `Container` | Viene attivato quando il container è completamente pronto | + +--- + +## Risoluzione dei Problemi + +- **Canvas non visibile** — Assicurati che il contenitore padre abbia dimensioni esplicite (`height: 100%`, `height: 100vh` o un valore fisso in pixel). +- **`loadFull is not a function`** — Verifica che `tsparticles` sia installato e che stai importando `loadFull` da `tsparticles` (non da `@tsparticles/engine`). +- **Reattività non funzionante** — Assicurati che `options` sia una variabile reattiva (`$:` o `let` collegata a una fonte reattiva). Valori `const` puri non si aggiorneranno. +- **SvelteKit schermata bianca** — Importa `@tsparticles/svelte` dinamicamente o usa la protezione `browser` come mostrato nella sezione SvelteKit sopra. +- **Errori TypeScript per `event.detail`** — Usa i tipi `CustomEvent` e `CustomEvent` per i gestori di eventi. diff --git a/websites/website/docs/it/guides/vanilla.md b/websites/website/docs/it/guides/vanilla.md new file mode 100644 index 00000000000..6114dd65c06 --- /dev/null +++ b/websites/website/docs/it/guides/vanilla.md @@ -0,0 +1,889 @@ +--- +title: Guida a Vanilla JS +description: Guida completa per integrare tsParticles con JavaScript puro. +--- + +# Guida a Vanilla JS + +## Indice dei Contenuti + +1. [Per Iniziare](#per-iniziare) +2. [Particelle di Base](#particelle-di-base) +3. [Effetto Coriandoli](#effetto-coriandoli) +4. [Effetto Fuochi d'Artificio](#effetto-fuochi-dartificio) +5. [Effetto Nastri](#effetto-nastri) +6. [Effetto Neve](#effetto-neve) +7. [Effetto Rete / Collegamenti](#effetto-rete-collegamenti) +8. [Effetto Stelle](#effetto-stelle) +9. [Configurazione Personalizzata](#configurazione-personalizzata) +10. [Contenitori Multipli](#contenitori-multipli) +11. [Controlli Dinamici](#controlli-dinamici) + +--- + +## Per Iniziare + +### CDN (avvio rapido) + +Aggiungi un `
` come contenitore e i tag script nel tuo HTML. Devi includere almeno il motore + un bundle, e devi chiamare il loader prima di `tsParticles.load()`. + +```html + + + + + + tsParticles – Per Iniziare + + + +
+ + + + + + +``` + +### npm + +```bash +npm install @tsparticles/engine @tsparticles/slim +``` + +Poi importalo e usalo: + +```javascript +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +(async () => { + await loadSlim(tsParticles); + + await tsParticles.load({ + id: "tsparticles", + options: { + /* ... */ + }, + }); +})(); +``` + +> **Nota:** Il solo `@tsparticles/engine` non disegna nulla. Devi installare un bundle (`@tsparticles/slim` consigliato) o plugin individuali per ottenere forme visibili. + +--- + +## Particelle di Base + +Una configurazione minima che visualizza 100 particelle con forma circolare, colori casuali e movimento delicato. In v4, i colori delle particelle vengono impostati tramite `paint` invece della vecchia proprietà `color`. + +```html + + + + + + Particelle di Base + + + +
+ + + + + + +``` + +--- + +## Effetto Coriandoli + +Usa il bundle dedicato `@tsparticles/confetti` per un'esplosione festosa con una singola chiamata di funzione. + +```html + + + + + + Coriandoli + + + + + + + + + +``` + +--- + +## Effetto Fuochi d'Artificio + +Uno spettacolo pirotecnico usando il bundle dedicato `@tsparticles/fireworks` con effetti sonori. + +```html + + + + + + Fuochi d'Artificio + + + + + + + +``` + +--- + +## Effetto Nastri + +Usa il bundle dedicato `@tsparticles/ribbons` per animazioni fluide di nastri che reagiscono alla posizione del mouse. + +```html + + + + + + Nastri + + + + + + + +``` + +--- + +## Effetto Neve + +Delicati fiocchi di neve che cadono usando il catalogo preset `@tsparticles/configs`. + +```html + + + + + + Effetto Neve + + + +
+ + + + + + + +``` + +In alternativa, usando il pacchetto preset autonomo: + +```html + + + + +``` + +--- + +## Effetto Rete / Collegamenti + +Un classico visuale di nodi connessi con interattività del mouse. Il bundle `@tsparticles/slim` include l'interazione dei collegamenti e la modalità di presa con il mouse. + +```html + + + + + + Rete / Collegamenti + + + +
+ + + + + + +``` + +--- + +## Effetto Stelle + +Un cielo stellato notturno usando il catalogo preset `@tsparticles/configs`. + +```html + + + + + + Effetto Stelle + + + +
+ + + + + + + +``` + +In alternativa, usando il pacchetto preset autonomo: + +```html + + + + +``` + +--- + +## Configurazione Personalizzata + +Crea una configurazione da zero con sfondo sfumato, effetti interattivi al passaggio del mouse e molteplici tipi di forma usando il bundle slim. + +```html + + + + + + Configurazione Personalizzata + + + +

Configurazione Personalizzata

+
+ + + + + + +``` + +--- + +## Contenitori Multipli + +Esegui più istanze indipendenti di particelle sulla stessa pagina, ciascuna con la propria configurazione. + +```html + + + + + + Contenitori Multipli + + + +
+
+
+
+ + + + + + +``` + +--- + +## Controlli Dinamici + +Avvia, ferma, metti in pausa e cambia tema a livello di programmazione in fase di esecuzione. + +```html + + + + + + Controlli Dinamici + + + +
+
+ + + + + + +
+ + + + + + +``` + +--- + +Ora hai coperto tutti i principali modelli di integrazione Vanilla JS per tsParticles v4. Ogni esempio è un file HTML autonomo che puoi aprire nel tuo browser per vedere tsParticles in azione. diff --git a/websites/website/docs/it/guides/vue3.md b/websites/website/docs/it/guides/vue3.md new file mode 100644 index 00000000000..4d00d20bb7b --- /dev/null +++ b/websites/website/docs/it/guides/vue3.md @@ -0,0 +1,622 @@ +--- +title: Integrazione Vue 3 +description: Guida passo-passo per integrare tsParticles in applicazioni Vue 3 usando @tsparticles/vue3. +--- + +# Integrazione Vue 3 + +Il pacchetto `@tsparticles/vue3` fornisce un componente e un sistema di plugin Vue 3 nativi per tsParticles. Questa guida copre tutto, dalla configurazione base ai pattern avanzati come il cambio tema dinamico e i preset personalizzati. + +--- + +## Installazione + +```bash +npm install @tsparticles/vue3 @tsparticles/engine +``` + +Installa opzionalmente un preset o il bundle completo: + +```bash +# Bundle completo (tutte le funzionalità) +npm install tsparticles + +# Preset specifici +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars + +# Configurazioni utility +npm install @tsparticles/configs +``` + +--- + +## Utilizzo Base + +Registra il plugin nel punto di ingresso della tua app, poi usa il componente `` ovunque. + +### Punto di ingresso app (`main.ts`) + +```typescript +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +const app = createApp(App); + +app.use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, +}); + +app.mount("#app"); +``` + +### Componente (`App.vue`) + +```vue + + + +``` + +--- + +## Usare `particlesInit` con il Componente + +Se preferisci non usare il plugin globale, passa una callback `init` direttamente: + +```vue + + + +``` + +--- + +## Eventi + +Il componente emette diversi eventi del ciclo di vita: + +```vue + + + +``` + +--- + +## Effetto Coriandoli + +Usa il preset confetti per celebrazioni: + +```bash +npm install @tsparticles/preset-confetti +``` + +```vue + + + +``` + +Per un'esplosione singola, carica il preset poi chiama `tsParticles.load()` programmaticamente all'interno di un metodo. + +--- + +## Effetto Fuochi d'Artificio + +Il preset fireworks crea esplosioni di particelle ad alto impatto: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```vue + + + +``` + +> **Suggerimento:** Il preset fireworks richiede molte risorse. Attivalo su interazione dell'utente (es. click su pulsante) tramite un `v-if` collegato al componente. + +--- + +## Effetto Neve + +Simula la neve che cade con il preset snow: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +--- + +## Particelle Interattive + +Aggiungi modalità di interattività al passaggio del mouse e al click: + +```vue + + + +``` + +Modalità di interazione disponibili: `grab`, `repulse`, `bubble`, `connect`, `push`, `remove`, `trail`, `attract`, `light`. + +--- + +## Cambio Tema + +Cambia dinamicamente i temi delle particelle in fase di esecuzione aggiornando l'oggetto opzioni reattivo: + +```vue + + + +``` + +In alternativa, usa l'opzione [themes](https://particles.js.org/docs/interfaces/Options_Interfaces_IOptions.IOptions.html#themes) integrata e la proprietà `theme` sul container per un cambio senza configurazione. + +--- + +## Preset Personalizzato da @tsparticles/configs + +Il pacchetto `@tsparticles/configs` esporta oggetti di configurazione predefiniti: + +```bash +npm install @tsparticles/configs +``` + +```vue + + + +``` + +Esplora le configurazioni disponibili nel pacchetto `@tsparticles/configs` per layout pronti all'uso. + +--- + +## Approcci all'Inizializzazione del Motore + +Ci sono due modi per inizializzare il motore: + +### 1. Plugin Globale (consigliato) + +```typescript +// main.ts +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +createApp(App) + .use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, + }) + .mount("#app"); +``` + +Il motore è quindi disponibile globalmente e tutte le istanze `` lo condividono. + +### 2. Init a Livello di Componente + +Passa una callback `:init` a ciascuna istanza ``. Utile quando diversi componenti necessitano di set diversi di plugin: + +```vue + +``` + +### 3. Particles Provider (Composition API) + +Usa il provider per accedere al motore programmaticamente: + +```vue + +``` + +--- + +## Esportazioni Nominative + TypeScript + +Esempio TypeScript completo con tutti gli elementi insieme: + +```vue + + + +``` + +--- + +## Riferimento API + +| Prop | Tipo | Default | Descrizione | +| --------- | ----------------------------------- | --------------- | ------------------------------------ | +| `id` | `string` | `"tsparticles"` | ID dell'elemento canvas | +| `options` | `ISourceOptions` | `{}` | Configurazione particelle | +| `init` | `(engine: Engine) => Promise` | — | Callback di inizializzazione motore | +| `url` | `string` | — | URL per caricare configurazione JSON | + +| Evento | Payload | Descrizione | +| ------------------- | ----------- | ---------------------------------------------------------------- | +| `@particles-loaded` | `Container` | Viene attivato quando il container è completamente inizializzato | +| `@particles-init` | `Engine` | Viene attivato dopo che il motore è inizializzato | + +--- + +## Risoluzione dei Problemi + +- **Errore: `tsparticles is not defined`** — Assicurati che `tsparticles` (o i preset necessari) siano caricati all'interno della callback `init` prima che il componente venga renderizzato. +- **Canvas non visibile** — Verifica che il contenitore padre abbia un'altezza non zero. Aggiungi una regola CSS come `#tsparticles { height: 100vh; }`. +- **Problemi di performance** — Riduci `fpsLimit`, diminuisci `particles.number.value` o disabilita `detectRetina` su dispositivi meno potenti. +- **SSR (Nuxt)** — Il componente `` è solo client. Avvolgilo in `` o usa la direttiva `client:only`. diff --git a/websites/website/docs/it/guides/webcomponents.md b/websites/website/docs/it/guides/webcomponents.md new file mode 100644 index 00000000000..b47af8454a6 --- /dev/null +++ b/websites/website/docs/it/guides/webcomponents.md @@ -0,0 +1,359 @@ +# Web Components + +Usa tsParticles con Web Components nativi tramite il pacchetto `@tsparticles/webcomponents`. Questo approccio non richiede framework — solo JavaScript puro e elementi personalizzati. + +## Installazione + +### Via CDN + +Includi il core tsParticles e il bundle Web Components: + +```html + + +``` + +### Via npm + Build + +```bash +npm install @tsparticles/webcomponents tsparticles +``` + +Poi importa nel tuo bundle JavaScript: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; +``` + +## Inizializzazione del Motore + +Prima che l'elemento `` possa renderizzare, il motore deve essere inizializzato con le funzionalità necessarie. Chiama `initParticlesEngine` con una callback che carica i plugin desiderati: + +```javascript +import { initParticlesEngine } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +> **Perché `loadFull`?** Registra tutte le forme integrate (cerchio, quadrato, poligono, immagine, ecc.), interazioni (hover, click) e aggiornamenti (opacità, dimensione, colore, ecc.). Per un bundle più piccolo, usa `tsparticles-slim` o seleziona plugin individuali. + +## Definire l'Elemento Personalizzato + +Dopo l'inizializzazione del motore, registra l'elemento personalizzato ``: + +```javascript +import { defineParticlesElement } from "@tsparticles/webcomponents"; + +defineParticlesElement(); +``` + +Questo registra il tag `web-particles` con il `CustomElementRegistry` del browser. È sicuro chiamarlo più volte — le registrazioni duplicate vengono ignorate. + +## Utilizzo Base + +Una volta che sia `initParticlesEngine` che `defineParticlesElement` sono stati eseguiti, usa l'elemento direttamente in HTML: + +```html + + + + + + tsParticles Web Components + + + + + + + +``` + +## Configurazione Personalizzata + +L'elemento `` accetta la configurazione tramite la proprietà `options` (oggetto JavaScript) o tramite JSON nell'attributo `options`. + +### Tramite Proprietà JavaScript + +```javascript +const el = document.querySelector("web-particles"); +el.options = { + background: { color: "#000000" }, + fpsLimit: 60, + particles: { + color: { value: ["#ff0000", "#00ff00", "#0000ff"] }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { value: 60 }, + opacity: { value: 0.6 }, + shape: { type: ["circle", "square"] }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + repulse: { distance: 200 }, + push: { quantity: 4 }, + }, + }, +}; +``` + +### Tramite Attributo HTML (JSON) + +```html + +``` + +> Quando usi l'attributo `options`, il valore deve essere JSON valido. L'assegnazione tramite proprietà è preferibile per configurazioni complesse. + +## Creazione Dinamica + +Puoi creare elementi `` interamente in JavaScript e aggiungerli al DOM in qualsiasi momento: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +defineParticlesElement(); + +function createParticles(container, config) { + const el = document.createElement("web-particles"); + el.id = "dynamic-particles"; + el.style.position = "absolute"; + el.style.width = "100%"; + el.style.height = "100%"; + el.style.top = "0"; + el.style.left = "0"; + el.options = config; + container.appendChild(el); + return el; +} + +// Utilizzo +const particles = createParticles(document.body, { + background: { color: "#1a1a2e" }, + particles: { + number: { value: 100 }, + links: { enable: true, color: "#e94560" }, + move: { enable: true, speed: 1 }, + }, +}); +``` + +## Estendere l'Elemento Personalizzato + +Puoi creare una sottoclasse di `ParticlesElement` per creare il tuo elemento personalizzato con configurazione incorporata: + +```javascript +import { initParticlesEngine, ParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +class MyParticlesBackground extends ParticlesElement { + constructor() { + super(); + this.style.position = "fixed"; + this.style.top = "0"; + this.style.left = "0"; + this.style.width = "100%"; + this.style.height = "100%"; + this.style.zIndex = "-1"; + } + + connectedCallback() { + this.options = { + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true, speed: 2 }, + }, + }; + super.connectedCallback(); + } +} + +customElements.define("my-particles-bg", MyParticlesBackground); +``` + +Utilizzo: + +```html + +``` + +## Accesso e Controllo del Container + +L'elemento personalizzato espone l'istanza `Container` di tsParticles per il controllo imperativo: + +```javascript +const el = document.querySelector("web-particles"); + +// Accedi al container (disponibile dopo connectedCallback) +const container = el.container; +container?.pause(); +container?.play(); + +// Distruggi e pulisci +el.dispose(); +``` + +## Esempio Completo + +Una pagina HTML completa che usa il modulo Web Components con script CDN: + +```html + + + + + + Demo Web Components tsParticles + + + +
+

tsParticles + Web Components

+

Elementi personalizzati nativi, nessun framework richiesto.

+
+ + + + + + +``` + +## Riferimento API + +| Esportazione / Proprietà | Tipo | Descrizione | +| ------------------------------- | ------------------------ | ---------------------------------------------------------- | +| `initParticlesEngine(callback)` | `function` | Inizializza il motore tsParticles con caricatori plugin | +| `defineParticlesElement()` | `function` | Registra l'elemento personalizzato `` | +| `ParticlesElement` | `class` | Classe base che puoi estendere per elementi personalizzati | +| `element.options` | `ISourceOptions` | Legge/imposta l'oggetto di configurazione particelle | +| `element.container` | `Container \| undefined` | Riferimento in sola lettura al `Container` sottostante | +| `element.dispose()` | `function` | Distrugge l'istanza delle particelle e libera risorse | diff --git a/websites/website/docs/it/guides/wordpress.md b/websites/website/docs/it/guides/wordpress.md new file mode 100644 index 00000000000..ac20ece3d74 --- /dev/null +++ b/websites/website/docs/it/guides/wordpress.md @@ -0,0 +1,314 @@ +--- +title: Guida WordPress +description: Guida completa per integrare tsParticles con WordPress usando il plugin, blocchi, shortcode e integrazione tema. +--- + +# Guida WordPress + +## Indice dei Contenuti + +1. [Installazione](#installazione) +2. [Attivazione del Plugin](#attivazione-del-plugin) +3. [Utilizzo Widget e Blocco](#utilizzo-widget-e-blocco) +4. [Utilizzo Shortcode](#utilizzo-shortcode) +5. [Configurazione tramite Filtro PHP](#configurazione-tramite-filtro-php) +6. [Configurazione Personalizzata tramite Filtro](#configurazione-personalizzata-tramite-filtro) +7. [Integrazione Tema](#integrazione-tema) + +--- + +## Installazione + +Il plugin tsParticles per WordPress è disponibile nella Directory dei Plugin di WordPress. Installalo direttamente dalla dashboard di amministrazione di WordPress. + +### Dalla Dashboard WordPress + +1. Vai su **Plugin → Aggiungi Nuovo** +2. Cerca "tsParticles" +3. Clicca **Installa Ora** sul plugin tsParticles +4. Clicca **Attiva** + +### Installazione Manuale + +1. Scarica il file ZIP del plugin dalla Directory dei Plugin di WordPress o dalla [pagina delle release](https://github.com/tsparticles/wordpress/releases) +2. Vai su **Plugin → Aggiungi Nuovo → Carica Plugin** +3. Scegli il file ZIP e clicca **Installa Ora** +4. Clicca **Attiva** + +--- + +## Attivazione del Plugin + +Una volta attivato, il plugin registra: + +- Un **blocco Gutenberg** chiamato "tsParticles" disponibile nell'inseritore di blocchi +- Uno **shortcode** `[tsparticles]` per l'uso nell'Editor Classico o nei template PHP personalizzati +- Un **filtro PHP** `tsparticles_options` per gli sviluppatori per iniettare la configurazione programmaticamente +- Asset front-end (JavaScript e CSS) che vengono accodati solo quando il blocco o lo shortcode è presente sulla pagina + +Dopo l'attivazione, puoi verificare che il plugin funzioni visitando **Impostazioni → tsParticles** nella barra laterale di amministrazione di WordPress, dove potrebbe essere disponibile una pagina di impostazioni di base a seconda della versione del plugin. + +--- + +## Utilizzo Widget e Blocco + +Il plugin tsParticles aggiunge un blocco Gutenberg personalizzato per l'editor a blocchi (WordPress 5.0+). + +### Aggiungere il Blocco + +1. Modifica qualsiasi articolo o pagina con l'editor a blocchi (Gutenberg) +2. Clicca sul pulsante **+** (Aggiungi Blocco) +3. Cerca "tsParticles" o "Particelle" +4. Clicca sul blocco **tsParticles** per inserirlo + +### Impostazioni del Blocco + +Una volta inserito, il pannello di ispezione del blocco (sul lato destro) fornisce le impostazioni: + +- **ID Container** — un ID HTML univoco per il container delle particelle (predefinito: `tsparticles`) +- **Larghezza / Altezza** — imposta dimensioni esplicite o usa la modalità a schermo intero +- **Z-Index** — controlla la stratificazione rispetto ad altri contenuti +- **Configurazione** — incolla un oggetto opzioni JSON per personalizzare completamente l'aspetto delle particelle + +Per aree widget o sidebar del tema che non supportano blocchi, usa invece l'approccio [Shortcode](#utilizzo-shortcode). + +--- + +## Utilizzo Shortcode + +Usa lo shortcode `[tsparticles]` nell'Editor Classico, blocchi HTML personalizzati o direttamente nei file template PHP per incorporare sfondi di particelle ovunque nel tuo sito. + +### Shortcode Base + +``` +[tsparticles] +``` + +Questo renderizza la configurazione predefinita delle particelle (semplici cerchi fluttuanti su sfondo scuro). + +### Shortcode con Opzioni + +Passa la configurazione JSON direttamente nello shortcode usando l'attributo `options`: + +``` +[tsparticles options='{"particles":{"number":{"value":50},"color":{"value":"#ff0000"},"shape":{"type":"circle"},"opacity":{"value":0.5},"size":{"value":{"min":1,"max":3}},"move":{"enable":true,"speed":1,"outModes":{"default":"bounce"}}},"background":{"color":"#1a1a2e"}}'] +``` + +### Shortcode nei Template PHP + +```php +// Nel tuo tema header.php o footer.php +echo do_shortcode('[tsparticles]'); +``` + +Oppure con opzioni personalizzate: + +```php +$options = [ + 'particles' => [ + 'number' => ['value' => 80], + 'color' => ['value' => '#00d4ff'], + 'shape' => ['type' => 'circle'], + 'links' => [ + 'enable' => true, + 'distance' => 150, + 'color' => '#00d4ff', + 'opacity' => 0.3, + ], + 'move' => [ + 'enable' => true, + 'speed' => 1.5, + 'outModes' => ['default' => 'bounce'], + ], + ], + 'background' => ['color' => '#0d1117'], +]; + +echo do_shortcode('[tsparticles options=\'' . wp_json_encode($options) . '\']'); +``` + +--- + +## Configurazione tramite Filtro PHP + +Il plugin espone un filtro `tsparticles_options` che ti permette di sovrascrivere o estendere la configurazione delle particelle dal file `functions.php` del tuo tema o da un plugin personalizzato. Questo è l'approccio consigliato per gli sviluppatori perché mantiene la configurazione in PHP ed evita JSON inline. + +### Filtro Base + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + $options['background'] = ['color' => '#0d1117']; + $options['particles']['number']['value'] = 100; + $options['particles']['color']['value'] = '#00d4ff'; + $options['particles']['shape']['type'] = 'circle'; + $options['particles']['opacity']['value'] = 0.6; + $options['particles']['size']['value'] = ['min' => 2, 'max' => 5]; + $options['particles']['links']['enable'] = true; + $options['particles']['links']['distance'] = 150; + $options['particles']['links']['color'] = '#00d4ff'; + $options['particles']['links']['opacity'] = 0.3; + $options['particles']['move']['enable'] = true; + $options['particles']['move']['speed'] = 1.5; + $options['particles']['move']['outModes']['default'] = 'bounce'; + return $options; +}); +``` + +Questo filtro viene eseguito prima che lo shortcode o il blocco venga renderizzato, quindi qualsiasi istanza di tsParticles sulla pagina riceve la configurazione personalizzata. + +--- + +## Configurazione Personalizzata tramite Filtro + +Ecco una configurazione personalizzata completa che dimostra tutta la potenza del filtro — inclusa interattività, tipi di forma multipli e supporto tema. + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + + // Sfondo a schermo intero + $options['fullScreen'] = [ + 'enable' => true, + 'zIndex' => -1, + ]; + + $options['fpsLimit'] = 60; + + // Impostazioni particelle + $options['particles'] = [ + 'number' => [ + 'value' => 60, + 'density' => ['enable' => true, 'width' => 800, 'height' => 800], + ], + 'color' => [ + 'value' => ['#ff6b6b', '#feca57', '#48dbfb', '#ff9ff3', '#54a0ff'], + ], + 'shape' => [ + 'type' => ['circle', 'triangle', 'polygon'], + 'options' => [ + 'polygon' => ['sides' => 6], + ], + ], + 'opacity' => [ + 'value' => ['min' => 0.4, 'max' => 0.8], + ], + 'size' => [ + 'value' => ['min' => 3, 'max' => 8], + ], + 'links' => [ + 'enable' => true, + 'distance' => 200, + 'color' => '#ffffff', + 'opacity' => 0.15, + 'width' => 1, + ], + 'move' => [ + 'enable' => true, + 'speed' => 2, + 'direction' => 'none', + 'random' => true, + 'straight' => false, + 'outModes' => ['default' => 'out'], + ], + ]; + + // Interattività + $options['interactivity'] = [ + 'events' => [ + 'onHover' => ['enable' => true, 'mode' => 'attract'], + 'onClick' => ['enable' => true, 'mode' => 'repulse'], + ], + 'modes' => [ + 'attract' => ['distance' => 200, 'duration' => 0.4, 'factor' => 1], + 'repulse' => ['distance' => 200, 'duration' => 0.4], + ], + ]; + + // Sfondo + $options['background'] = [ + 'color' => '#0f0f23', + ]; + + // Supporto tema — modalità chiara + $options['themes'] = [ + [ + 'name' => 'light', + 'default' => ['value' => false], + 'options' => [ + 'background' => ['color' => '#f0f0f5'], + 'particles' => [ + 'color' => ['value' => ['#e74c3c', '#2ecc71', '#3498db', '#f1c40f']], + 'links' => ['color' => '#333333', 'opacity' => 0.2], + ], + ], + ], + ]; + + return $options; +}); +``` + +--- + +## Integrazione Tema + +Per rendere tsParticles uno sfondo persistente in tutto il tuo tema WordPress, aggiungi lo shortcode o una chiamata PHP diretta al file `header.php` o `footer.php` del tuo tema. + +### Sfondo nell'Header + +```php + + +
+ +
+ +``` + +### Stili per Sfondo a Schermo Intero + +Aggiungi il seguente CSS al file `style.css` del tuo tema o tramite `wp_add_inline_style`: + +```css +#tsparticles-background { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + z-index: -1; + pointer-events: none; +} + +/* Assicura che il contenuto appaia sopra le particelle */ +.site-content { + position: relative; + z-index: 1; +} +``` + +### Caricamento Condizionale + +Per caricare tsParticles solo su pagine specifiche: + +```php +// In functions.php — accoda solo nella pagina principale +add_action('wp', function () { + if (is_front_page()) { + add_filter('tsparticles_options', function (array $options): array { + $options['particles']['number']['value'] = 120; + $options['particles']['color']['value'] = '#ffffff'; + $options['particles']['move']['speed'] = 0.8; + $options['background']['color'] = '#1a1a2e'; + return $options; + }); + } +}); +``` + +Combina questo con il posizionamento del blocco o dello shortcode per uno sfondo di particelle performante e specifico per pagina. + +--- + +Ora hai tutto il necessario per integrare tsParticles in un sito WordPress. Che tu preferisca l'editor a blocchi, gli shortcode o il controllo PHP completo, ogni approccio ti offre uno sfondo di particelle unico con il minimo sforzo. diff --git a/websites/website/docs/ja/guide/bundles-all.md b/websites/website/docs/ja/guide/bundles-all.md index 9965040698b..73ecc190319 100644 --- a/websites/website/docs/ja/guide/bundles-all.md +++ b/websites/website/docs/ja/guide/bundles-all.md @@ -1,21 +1,42 @@ # Bundle: All -`@tsparticles/all` は公式機能をすべて読み込み、素早いプロトタイピングに向いています。 +`@tsparticles/all` は tsParticles リポジトリの**すべて**(あらゆる形状、インタラクション、アップデーター、エフェクト、パス、イージング、プラグイン、エクスポート)を読み込みます。最大のバンドルで、プロトタイピングとデモ向けです。 -## All を選ぶタイミング +## 含まれる機能 -- すべての機能をすぐ使いたい。 -- 素早く選択肢を試したい。 -- サイズよりセットアップ速度を優先したい。 +`tsparticles`(full)のすべてを継承し、さらに: + +**すべての形状:** 矢印、カード、cog、ハート、infinity、matrix、path、リボン、角丸多角形、角丸四角、スパイラル、スクワークル + +**すべての外部インタラクション:** cannon、light、particle、pop、particles-repulse + +**すべてのエフェクト:** バブル、フィルター、パーティクル、シャドウ、トレイル + +**すべてのパスジェネレーター:** branches、brownian、curl-noise、curves、fractal-noise、grid、levy、perlin-noise、polygon、random、simplex-noise、spiral、svg、zig-zag + +**すべてのイージング:** back、bounce、circ、cubic、elastic、expo、gaussian、linear、quad、quart、quint、sigmoid、sine、smoothstep + +**すべてのカラープラグイン:** HEX、HSL、RGB、HSV、HWB、LAB、LCH、Named、OKLAB、OKLCH + +**すべてのプラグイン:** アブソーバー、background-mask、canvas-mask、エミッター(全形状)、イージング(全種類)、export-image、export-json、export-video、infection、manual-particles、motion、poisson-disc、polygon-mask、responsive、sounds、themes、trail、zoom + +**すべてのアップデーター:** destroy、gradient、life、opacity、orbit、out-modes、paint、roll、rotate、size、tilt、twinkle、wobble + +## 使用すべきケース + +- 可能性を探るための迅速なプロトタイピング +- デモやショーケース +- サイズが重要でない開発環境 +- **本番環境には非推奨** — よりターゲットを絞ったバンドルを使用してください ## インストール +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/all ``` -## Setup example - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadAll } from "@tsparticles/all"; @@ -25,20 +46,48 @@ await loadAll(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { number: { value: 100 }, + shape: { type: "heart" }, move: { enable: true, speed: 2 }, }, }, }); ``` -## よくある落とし穴 +### CDN(script タグ) + +```html + + + +``` + +## `tsparticles` と `@tsparticles/all` の違い + +詳細な比較表は[バンドル full ページ](/ja/guide/bundles-full)を参照してください。 + +## よくある間違い -- 本番で、より小さい bundle で十分なのに all を使う。 -- `loadAll(...)` より先に `tsParticles.load(...)` を呼ぶ。 +- 本番環境で使用する — より小さいバンドル(`@tsparticles/slim` または `tsparticles`)を優先してください。 +- `loadAll(tsParticles)` より前に `tsParticles.load()` を呼ぶ。 ## 関連ページ -- 概要: [`/guide/bundles`](/ja/guide/bundles) -- インストール一覧: [`/guide/installation`](/ja/guide/installation) +- [バンドル概要](/ja/guide/bundles) +- [インストールガイド](/ja/guide/installation) diff --git a/websites/website/docs/ja/guide/bundles-basic.md b/websites/website/docs/ja/guide/bundles-basic.md index a4c82cdffaa..8b77d17c9d7 100644 --- a/websites/website/docs/ja/guide/bundles-basic.md +++ b/websites/website/docs/ja/guide/bundles-basic.md @@ -1,21 +1,46 @@ # Bundle: Basic -`@tsparticles/basic` は、最小ランタイムで超軽量に構成したい場合向けです。 +`@tsparticles/basic` は最も軽量なバンドルです。アニメーション可能な不透明度とサイズを持つ円が移動する、必要最小限の機能のみを含みます。 -## Basic を選ぶタイミング +## 含まれる機能 -- bundle サイズが最優先。 -- 必要なのは基本的な効果だけ。 -- 高度な plugins は不要。 +**形状:** 円 + +**アップデーター:** + +- paint(色) +- 不透明度 +- out-modes(画面外での動作) +- サイズ + +**プラグイン:** + +- move +- blend(色のブレンド) +- HEX、HSL、RGB カラープラグイン + +**含まれないもの:** + +- マウス/タッチインタラクション +- パーティクルリンク +- その他の形状(四角、星、画像、多角形など) +- エミッター、アブソーバー、サウンド +- 回転、life、roll、tilt、wobble + +## 使用すべきケース + +- バンドルサイズが最優先 +- 動くドットだけが必要 +- インタラクションや複雑な形状は不要 ## インストール +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/basic ``` -## Setup example - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadBasic } from "@tsparticles/basic"; @@ -25,20 +50,48 @@ await loadBasic(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#ffffff" }, particles: { number: { value: 50 }, - move: { enable: true, speed: 1.5 }, + color: { value: ["#5bc0eb", "#fde74c", "#9bc53d"] }, + size: { + value: { min: 300, max: 400 }, + animation: { enable: true, speed: 100 }, + }, + move: { enable: true, speed: 10 }, }, }, }); ``` -## よくある落とし穴 +### CDN(script タグ) + +```html + + + +``` + +## よくある間違い -- basic に含まれない plugin 機能を期待してしまう。 -- `loadBasic(...)` より先に `tsParticles.load(...)` を呼ぶ。 +- 含まれていない機能(例: `links`、マウスインタラクション)を期待する — これらは上位のバンドルが必要です。 +- `loadBasic(tsParticles)` より前に `tsParticles.load()` を呼ぶ — 形状とアップデーターがまだ登録されていません。 +- バンドルなしで `@tsparticles/engine` だけをインストールする — エンジン単体では何も描画しません。 ## 関連ページ -- 概要: [`/guide/bundles`](/ja/guide/bundles) -- インストール一覧: [`/guide/installation`](/ja/guide/installation) +- [バンドル概要](/ja/guide/bundles) +- [インストールガイド](/ja/guide/installation) diff --git a/websites/website/docs/ja/guide/bundles-confetti.md b/websites/website/docs/ja/guide/bundles-confetti.md index 6a55bc361d8..4d6f567b252 100644 --- a/websites/website/docs/ja/guide/bundles-confetti.md +++ b/websites/website/docs/ja/guide/bundles-confetti.md @@ -1,42 +1,83 @@ # Bundle: Confetti -`@tsparticles/confetti` は、最小セットアップで紙吹雪演出を行う特化 API です。 +`@tsparticles/confetti` は、1 回の関数呼び出しで紙吹雪エフェクトを作成するための簡略化された API を提供します。`tsParticles` を直接操作する必要はありません。 -## Confetti を選ぶタイミング +## 含まれる機能 -- 祝賀エフェクトを 1 call で実行したい。 -- engine を手動で配線したくない。 -- UI イベント向けにコンパクトな API が欲しい。 +**形状:** 円、ハート、カード(フランスのスート: ハート、ダイヤ、クラブ、スペード)、絵文字、画像、多角形、四角、星 + +**内部プラグイン:** エミッター、motion(ユーザーの動作軽減設定を尊重) + +**アップデーター:** life、roll、rotate、tilt、wobble + +**API:** `confetti(options)` または `confetti(canvasId, options)` + +## 使用すべきケース + +- 「おめでとう!」や「ハッピーバースデー!」ボタン +- 簡単な祝賀エフェクト +- エンジンを手動で設定したくない ## インストール +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/confetti ``` -## Setup example - ```ts import { confetti } from "@tsparticles/confetti"; +// 基本的なエフェクト await confetti({ - count: 80, - spread: 60, + particleCount: 100, + spread: 70, + origin: { x: 0.5, y: 0.5 }, }); -await confetti("canvas-id", { - count: 50, +// 特定のキャンバス上で +await confetti("my-canvas-id", { + particleCount: 50, angle: 90, spread: 45, + colors: ["#ff0000", "#00ff00", "#0000ff"], }); ``` -## よくある落とし穴 +### CDN(script タグ) + +```html + + +``` + +### 主要パラメーター + +| パラメーター | 型 | デフォルト | 説明 | +| --------------- | -------- | ------------ | -------------------------------------------------- | +| `particleCount` | number | 50 | 紙吹雪の数 | +| `spread` | number | 60 | 拡散角度(度) | +| `angle` | number | 90 | 方向(度、90 = 下向き) | +| `startVelocity` | number | 30 | 初速度 | +| `colors` | string[] | — | 紙吹雪の色 | +| `origin` | { x, y } | { 0.5, 0.5 } | 発生点(0-1) | +| `drift` | number | 0 | 水平方向のドリフト | +| `shapes` | string[] | — | 形状: "circle"、"heart"、"square"、"star"、"cards" | + +## よくある間違い -- `@tsparticles/confetti` から `tsParticles` が export されると思い込む。 -- 同じ canvas id を意図せず再利用する。 +- `@tsparticles/confetti` が `tsParticles` をエクスポートしていると思う — していません。 +- 同じ canvas ID を意図せず再利用する。 +- パフォーマンスを管理せずにループ内で `confetti` を呼ぶ — 適切な間隔を設定するか、アニメーション完了時に停止してください。 ## 関連ページ -- 概要: [`/guide/bundles`](/ja/guide/bundles) -- Playground bundles: [`/playground/bundles`](/ja/playground/bundles) +- [バンドル概要](/ja/guide/bundles) +- [Fireworks バンドル](/ja/guide/bundles-fireworks) diff --git a/websites/website/docs/ja/guide/bundles-fireworks.md b/websites/website/docs/ja/guide/bundles-fireworks.md index fc2f3e971e5..1abe570486e 100644 --- a/websites/website/docs/ja/guide/bundles-fireworks.md +++ b/websites/website/docs/ja/guide/bundles-fireworks.md @@ -1,44 +1,81 @@ # Bundle: Fireworks -`@tsparticles/fireworks` は、最小セットアップで花火演出を行う特化 API です。 +`@tsparticles/fireworks` は、1 回の関数呼び出しで花火エフェクトを作成するための簡略化された API を提供します。サウンド、カスタムカラー、インスタンス制御(一時停止/再生)をサポートします。 -## Fireworks を選ぶタイミング +## 含まれる機能 -- 花火アニメーションを 1 call で使いたい。 -- engine の直接 wiring は不要。 -- 祝賀 UI にコンパクトな API を使いたい。 +**形状:** 線、円(basic から) + +**内部プラグイン:** エミッター、emitters-shape-square、blend(ブレンド)、sounds + +**アップデーター:** destroy、life、paint、rotate + +**API:** `fireworks(options)` — 制御可能なインスタンスを返します + +## 使用すべきケース + +- 新年や祝賀エフェクト +- 祝賀 UI +- エンジンを手動で設定したくない ## インストール +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/fireworks ``` -## Setup example - ```ts import { fireworks } from "@tsparticles/fireworks"; +// 基本的なエフェクト const instance = await fireworks({ - colors: ["#ffffff", "#ff0000"], - sounds: false, + colors: ["#ffffff", "#ff0000", "#00ff00", "#0000ff"], + sounds: true, }); +// インスタンス制御 instance?.pause(); instance?.play(); -await fireworks("canvas-id", { +// 特定のキャンバス上で +await fireworks("my-canvas", { rate: 3, speed: { min: 10, max: 25 }, + sounds: false, }); ``` -## よくある落とし穴 +### CDN(script タグ) + +```html + + +``` + +### 主要パラメーター + +| パラメーター | 型 | デフォルト | 説明 | +| ------------ | ------------ | ---------- | --------------------- | +| `colors` | string[] | — | 爆発の色 | +| `rate` | number | — | 1 秒あたりの花火数 | +| `speed` | { min, max } | — | パーティクルの速度 | +| `sounds` | boolean | true | 効果音を有効にする | +| `gravity` | number | — | 重力(デフォルト: 0) | +| `opacity` | number | — | 不透明度(0-1) | +| `brightness` | { min, max } | — | 爆発の明るさ | + +## よくある間違い -- `@tsparticles/fireworks` から `tsParticles` が export されると思い込む。 -- 返された instance を管理せず `fireworks(...)` を繰り返し呼ぶ。 +- `@tsparticles/fireworks` が `tsParticles` をエクスポートしていると思う — していません。 +- インスタンスを管理せずに `fireworks()` をループ内で呼ぶ — エフェクトはすでに継続的です。 +- ページ離脱時にインスタンスを停止しない — `instance?.pause()` または `instance?.stop()` を呼んでください。 ## 関連ページ -- 概要: [`/guide/bundles`](/ja/guide/bundles) -- Playground bundles: [`/playground/bundles`](/ja/playground/bundles) +- [バンドル概要](/ja/guide/bundles) +- [Confetti バンドル](/ja/guide/bundles-confetti) diff --git a/websites/website/docs/ja/guide/bundles-full.md b/websites/website/docs/ja/guide/bundles-full.md index f9806c3ceac..04acc23098c 100644 --- a/websites/website/docs/ja/guide/bundles-full.md +++ b/websites/website/docs/ja/guide/bundles-full.md @@ -1,21 +1,48 @@ -# Bundle: tsparticles (Full) +# Bundle: tsparticles(Full) -`tsparticles` は full bundle で、1 つの loader で幅広い公式機能をまとめて使えます。 +`tsparticles`(npm: `tsparticles`、ローダー: `loadFull`)は公式のフルバンドルです。Slim のすべてに加え、エミッター、アブソーバー、テキスト形状、高度なアニメーション(ウィブル、ロール、ティルト、トゥインクル、デストロイ)を含みます。 -## tsparticles (Full) を選ぶタイミング +## 含まれる機能 -- 多くの公式機能を plugin の個別選択なしで使いたい。 -- 微調整の前に、production 向けの完全な土台を用意したい。 -- `tsParticles` API で engine を直接コントロールしたい。 +`@tsparticles/slim` のすべてを継承し、さらに: + +**追加形状:** テキスト(カスタムフォント対応) + +**追加外部インタラクション:** + +- drag(マウスでパーティクルをドラッグ) +- trail(マウス後方のパーティクルトレイル) + +**追加アップデーター:** + +- destroy(パーティクル破壊アニメーション) +- roll(回転) +- tilt(3D 傾き) +- twinkle(断続的なきらめき) +- wobble(振動) + +**プラグイン:** + +- アブソーバー(パーティクルを吸い込むブラックホール) +- エミッター(継続的なパーティクル生成源) +- emitters-shape-circle、emitters-shape-square(エミッター形状) + +## 使用すべきケース + +- エミッター(パーティクルの継続的生成)が必要 +- アブソーバー(パーティクルの吸い込み)が必要 +- カスタムフォントを使用したテキスト形状が必要 +- 高度なアニメーション(ウィブル、ティルト、ロール、トゥインクル)が必要 +- 個別プラグインに進む前の良いステップ ## インストール +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine tsparticles ``` -## Setup example - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadFull } from "tsparticles"; @@ -25,20 +52,65 @@ await loadFull(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { - number: { value: 100 }, - move: { enable: true, speed: 2 }, + number: { value: 50 }, + shape: { type: "text", options: { text: ["🔥", "✨", "⭐"] } }, + size: { value: 24 }, + move: { enable: true, speed: 1 }, + wobble: { enable: true, distance: 10 }, + }, + emitters: { + direction: "top", + rate: { quantity: 2, delay: 0.3 }, }, }, }); ``` -## よくある落とし穴 +### CDN(script タグ) + +```html + + + +``` + +## `tsparticles` と `@tsparticles/all` の違い + +| 項目 | `tsparticles`(full) | `@tsparticles/all` | +| ---------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------- | +| サイズ | 中程度 | 非常に大きい | +| 形状 | 円、四角、星、多角形、線、画像、絵文字、テキスト | すべての形状(ハート、カード、矢印、スパイラル、cog、角丸四角など) | +| インタラクション | Slim + drag + trail | すべて(cannon、light、pop、particle、repulse) | +| パス | Quad イージングのみ | 14 のパスジェネレーター | +| エフェクト | なし | 5 エフェクト(バブル、フィルター、シャドウなど) | +| エクスポート | なし | 画像、JSON、動画 | +| 追加プラグイン | アブソーバー、エミッター | すべて(sounds、themes、trail、zoom、polygon-mask、canvas-mask、background-mask など) | +| イージング | Quad | 15 のイージング | + +## よくある間違い -- `loadFull(...)` より先に `tsParticles.load(...)` を呼ぶ。 -- `@tsparticles/all` と同じパッケージだと思い込む(別 bundle です)。 +- `tsparticles` と `@tsparticles/all` を混同する — これらは異なるパッケージです。 +- `loadFull(tsParticles)` より前に `tsParticles.load()` を呼ぶ。 +- npm パッケージは `tsparticles`(`@tsparticles/full` ではありません)、ローダーは `loadFull` です。 ## 関連ページ -- 概要: [`/guide/bundles`](/ja/guide/bundles) -- インストール一覧: [`/guide/installation`](/ja/guide/installation) +- [バンドル概要](/ja/guide/bundles) +- [インストールガイド](/ja/guide/installation) diff --git a/websites/website/docs/ja/guide/bundles-particles.md b/websites/website/docs/ja/guide/bundles-particles.md index 785005c997f..867e4d3a763 100644 --- a/websites/website/docs/ja/guide/bundles-particles.md +++ b/websites/website/docs/ja/guide/bundles-particles.md @@ -1,42 +1,98 @@ # Bundle: Particles -`@tsparticles/particles` は、シンプルな粒子背景向けの特化 API を提供します。 +`@tsparticles/particles` は、インタラクティブなパーティクル背景を作成するための簡略化された API を提供します。`@tsparticles/basic` よりもリッチな代替手段で、手動のエンジン設定ではなく専用 API を使用します。 -## Particles を選ぶタイミング +## 含まれる機能 -- 粒子背景をすばやく導入したい。 -- engine/plugins を手動で配線したくない。 -- コンパクトなアプリ向け API を使いたい。 +**形状:** 円(basic から) + +**内部プラグイン:** interactivity(リンク、衝突) + +**インタラクション:** リンク(パーティクル接続)、衝突 + +**API:** `particles(options)` または `particles(canvasId, options)` + +## 使用すべきケース + +- Web サイトのパーティクル背景 +- パーティクルリンク付き背景(ノード風エフェクト) +- エンジンを手動で設定したくない ## インストール +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/particles ``` -## Setup example - ```ts import { particles } from "@tsparticles/particles"; +// リンク付き背景 await particles({ count: 120, links: true, - linksColor: "#0ff", + color: "#ffffff", + linksColor: "#00d8ff", + radius: 3, + speed: 2, + opacity: 0.8, }); -await particles("canvas-id", { +// 特定のキャンバス上で +await particles("my-canvas", { count: 80, shape: ["circle", "square"], + links: true, }); + +// カスタムカラーで +await particles({ + count: 100, + color: ["#ff6b6b", "#4ecdc4", "#45b7d1"], + links: false, +}); +``` + +### CDN(script タグ) + +```html + + ``` -## よくある落とし穴 +### 主要パラメーター + +| パラメーター | 型 | デフォルト | 説明 | +| ------------ | ------------------ | ---------- | ------------------ | +| `count` | number | 50 | パーティクルの数 | +| `radius` | number | 3 | パーティクルの半径 | +| `speed` | number | 2 | 移動速度 | +| `opacity` | number | 0.8 | 不透明度(0-1) | +| `color` | string \| string[] | "#ffffff" | パーティクルの色 | +| `links` | boolean | false | リンクを表示 | +| `linksColor` | string | "#ffffff" | リンクの色 | +| `linksWidth` | number | 1 | リンクの太さ | +| `shape` | string[] | ["circle"] | パーティクルの形状 | + +## よくある間違い -- `@tsparticles/particles` から `tsParticles` が export されると思い込む。 -- 同じ canvas id を意図せず再利用する。 +- `@tsparticles/particles` が `tsParticles` をエクスポートしていると思う — していません。 +- 同じ canvas ID を意図せず再利用する。 +- 高度な形状(星、多角形)を期待する — particles バンドルは basic ベースで円のみを使用します。 ## 関連ページ -- 概要: [`/guide/bundles`](/ja/guide/bundles) -- Playground bundles: [`/playground/bundles`](/ja/playground/bundles) +- [バンドル概要](/ja/guide/bundles) +- [はじめに](/ja/guide/getting-started) diff --git a/websites/website/docs/ja/guide/bundles-slim.md b/websites/website/docs/ja/guide/bundles-slim.md index b4cc6c299bd..cf304a1e6a7 100644 --- a/websites/website/docs/ja/guide/bundles-slim.md +++ b/websites/website/docs/ja/guide/bundles-slim.md @@ -1,21 +1,61 @@ # Bundle: Slim -`@tsparticles/slim` は、ほとんどのプロジェクトで推奨される標準バンドルです。 +`@tsparticles/slim` はほとんどのプロジェクトに推奨されるバンドルです。マウスインタラクション、複数の形状、パーティクルリンクを備えた、モダンなパーティクルアニメーションに必要なすべてを含みます。 -## Slim を選ぶタイミング +## 含まれる機能 -- サイズと機能のバランスを重視したい。 -- `tsParticles` の engine API を直接使いたい。 -- 一般的な shape/interactions を、全機能なしで使いたい。 +`@tsparticles/basic` のすべてを継承し、さらに: + +**形状:** 円、四角、星、多角形、線、画像、絵文字 + +**外部インタラクション(マウス/タッチ):** + +- attract +- bounce +- bubble +- connect +- destroy +- grab +- parallax +- pause +- push +- remove +- repulse +- slow + +**パーティクルインタラクション:** + +- attract +- 衝突 +- リンク(パーティクル接続) + +**追加アップデーター:** + +- life(ライフサイクル) +- 回転 + +**プラグイン:** + +- interactivity +- easing-quad +- HEX、HSL、RGB カラープラグイン + +## 使用すべきケース + +- ほとんどのプロジェクトの推奨開始点 +- 複数の形状(円、星、多角形、画像)が必要 +- マウスインタラクション(クリック、ホバー、バブル、リパルス)が必要 +- パーティクルリンクが必要 +- バンドルサイズと機能のバランスが良い ## インストール +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/slim ``` -## Setup example - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; @@ -25,21 +65,47 @@ await loadSlim(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#0b1020" }, particles: { number: { value: 80 }, + links: { enable: true, distance: 150 }, move: { enable: true, speed: 2 }, - links: { enable: true }, + shape: { type: ["circle", "star", "square"] }, }, }, }); ``` -## よくある落とし穴 +### CDN(script タグ) + +```html + + + +``` + +## よくある間違い -- `loadSlim(...)` より先に `tsParticles.load(...)` を呼ぶ。 -- engine と plugins のバージョンを混在させる。 +- `loadSlim(tsParticles)` より前に `tsParticles.load()` を呼ぶ。 +- エンジンとバンドルのバージョンが異なる — バージョンを揃えてください。 +- 上位バンドルの機能(エミッター、アブソーバー、テキスト、ウィブル)を期待する — `tsparticles`(full)または個別プラグインが必要です。 ## 関連ページ -- 概要: [`/guide/bundles`](/ja/guide/bundles) -- インストール一覧: [`/guide/installation`](/ja/guide/installation) +- [バンドル概要](/ja/guide/bundles) +- [インストールガイド](/ja/guide/installation) diff --git a/websites/website/docs/ja/guide/bundles.md b/websites/website/docs/ja/guide/bundles.md index 537b23aba46..75175febe15 100644 --- a/websites/website/docs/ja/guide/bundles.md +++ b/websites/website/docs/ja/guide/bundles.md @@ -1,104 +1,184 @@ -# Bundles ガイド - -このページでは、`tsParticles` の適切な bundle を選び、素早くセットアップする方法をまとめています。 - -## パッケージ比較 - -| パッケージ | 向いている用途 | セットアップ方式 | -| ------------------------ | ------------------------------------------------ | ---------------------------------------------- | -| `@tsparticles/basic` | さらに軽量な構成 | `tsParticles` + `await loadBasic(tsParticles)` | -| `@tsparticles/slim` | ほとんどの Web サイト/アプリ | `tsParticles` + `await loadSlim(tsParticles)` | -| `tsparticles` | 公式機能を広く含む full 構成を engine 制御で使う | `tsParticles` + `await loadFull(tsParticles)` | -| `@tsparticles/all` | 全機能を使った高速プロトタイプ | `tsParticles` + `await loadAll(tsParticles)` | -| `@tsparticles/confetti` | 1 回の呼び出しで紙吹雪演出 | `await confetti(options)` | -| `@tsparticles/fireworks` | 1 回の呼び出しで花火演出 | `await fireworks(options)` | -| `@tsparticles/particles` | シンプルな粒子背景 API | `await particles(options)` | -| `@tsparticles/ribbons` | 1 回の呼び出しで ribbons 演出 | `await ribbons(options)` | - -## Bundle ガイド - -- Basic: [`/guide/bundles-basic`](/ja/guide/bundles-basic) -- Slim: [`/guide/bundles-slim`](/ja/guide/bundles-slim) -- tsparticles (Full): [`/guide/bundles-full`](/ja/guide/bundles-full) -- All: [`/guide/bundles-all`](/ja/guide/bundles-all) -- Confetti: [`/guide/bundles-confetti`](/ja/guide/bundles-confetti) -- Fireworks: [`/guide/bundles-fireworks`](/ja/guide/bundles-fireworks) -- Particles: [`/guide/bundles-particles`](/ja/guide/bundles-particles) -- Ribbons(demo + docs): [`/demos/recipes/ribbons`](/ja/demos/recipes/ribbons) · - -## インストール - -用途に合うパッケージ経路をインストールします。 - -```bash -pnpm add @tsparticles/engine @tsparticles/basic -pnpm add @tsparticles/engine @tsparticles/slim -pnpm add @tsparticles/engine tsparticles -pnpm add @tsparticles/engine @tsparticles/all -pnpm add @tsparticles/confetti -pnpm add @tsparticles/fireworks -pnpm add @tsparticles/particles -pnpm add @tsparticles/ribbons +# バンドルガイド + +tsParticles はモジュール式です。`@tsparticles/engine` パッケージはコアエンジンのみを含みます。視覚効果を得るには、**形状**(何を描画するか)、**アップデーター**(アニメーション方法)、**インタラクション**(マウス/タッチへの反応)、**プラグイン**(追加機能)を登録する必要があります。これらはすべて**バンドル**を通じて行われます。 + +## バンドルのカテゴリ + +| カテゴリ | バンドル | API | +| ------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------ | +| エンジン + ローダー | `@tsparticles/basic`、`@tsparticles/slim`、`tsparticles`、`@tsparticles/all` | `tsParticles.load({ id, options })` | +| 専用 API | `@tsparticles/confetti`、`@tsparticles/fireworks`、`@tsparticles/particles`、`@tsparticles/ribbons` | `confetti({...})`、`fireworks({...})` など | + +## 機能比較 + +凡例: ● = 含む、○ = 含まない + +| 機能 | basic | slim | full(`tsparticles`) | all | +| --------------------------------------------------------------------------------------------------- | ----- | ---- | --------------------- | ---------------------- | +| **形状** | | | | | +| 円 | ● | ● | ● | ● | +| 四角 | ○ | ● | ● | ● | +| 星 | ○ | ● | ● | ● | +| 多角形 | ○ | ● | ● | ● | +| 線 | ○ | ● | ● | ● | +| 画像 | ○ | ● | ● | ● | +| 絵文字 | ○ | ● | ● | ● | +| テキスト | ○ | ○ | ● | ● | +| カード(スート) | ○ | ○ | ○ | ● | +| ハート | ○ | ○ | ○ | ● | +| 矢印 | ○ | ○ | ○ | ● | +| 角丸四角 | ○ | ○ | ○ | ● | +| 角丸多角形 | ○ | ○ | ○ | ● | +| スパイラル | ○ | ○ | ○ | ● | +| スクワークル | ○ | ○ | ○ | ● | +| Cog | ○ | ○ | ○ | ● | +| Infinity | ○ | ○ | ○ | ● | +| Matrix | ○ | ○ | ○ | ● | +| Path | ○ | ○ | ○ | ● | +| リボン | ○ | ○ | ○ | ● | +| **外部インタラクション(マウス/タッチ)** | | | | | +| Attract | ○ | ● | ● | ● | +| Bounce | ○ | ● | ● | ● | +| Bubble | ○ | ● | ● | ● | +| Connect | ○ | ● | ● | ● | +| Destroy | ○ | ● | ● | ● | +| Grab | ○ | ● | ● | ● | +| Parallax | ○ | ● | ● | ● | +| Pause | ○ | ● | ● | ● | +| Push | ○ | ● | ● | ● | +| Remove | ○ | ● | ● | ● | +| Repulse | ○ | ● | ● | ● | +| Slow | ○ | ● | ● | ● | +| Drag | ○ | ○ | ● | ● | +| Trail | ○ | ○ | ● | ● | +| Cannon | ○ | ○ | ○ | ● | +| Particle | ○ | ○ | ○ | ● | +| Pop | ○ | ○ | ○ | ● | +| Light | ○ | ○ | ○ | ● | +| **パーティクルインタラクション** | | | | | +| リンク | ○ | ● | ● | ● | +| 衝突 | ○ | ● | ● | ● | +| Attract | ○ | ● | ● | ● | +| Repulse | ○ | ○ | ○ | ● | +| **アップデーター(アニメーション)** | | | | | +| 不透明度 | ● | ● | ● | ● | +| サイズ | ● | ● | ● | ● | +| Out modes | ● | ● | ● | ● | +| 色(Paint) | ● | ● | ● | ● | +| 回転 | ○ | ● | ● | ● | +| Life | ○ | ● | ● | ● | +| Destroy | ○ | ○ | ● | ● | +| Roll | ○ | ○ | ● | ● | +| Tilt | ○ | ○ | ● | ● | +| Twinkle | ○ | ○ | ● | ● | +| Wobble | ○ | ○ | ● | ● | +| Gradient | ○ | ○ | ○ | ● | +| Orbit | ○ | ○ | ○ | ● | +| **プラグイン** | | | | | +| Move | ● | ● | ● | ● | +| Blend | ● | ● | ● | ● | +| エミッター | ○ | ○ | ● | ● | +| アブソーバー | ○ | ○ | ● | ● | +| Sounds | ○ | ○ | ○ | ● | +| Motion(ユーザー設定) | ○ | ○ | ○ | ● | +| Themes | ○ | ○ | ○ | ● | +| ポリゴンマスク | ○ | ○ | ○ | ● | +| キャンバスマスク | ○ | ○ | ○ | ● | +| 背景マスク | ○ | ○ | ○ | ● | +| エクスポート(画像、JSON、動画) | ○ | ○ | ○ | ● | +| Manual particles | ○ | ○ | ○ | ● | +| Responsive | ○ | ○ | ○ | ● | +| Trail | ○ | ○ | ○ | ● | +| Zoom | ○ | ○ | ○ | ● | +| Poisson disc | ○ | ○ | ○ | ● | +| **パス** | | | | | +| 任意のパス | ○ | ○ | ○ | ●(14 ジェネレーター) | +| **エフェクト** | | | | | +| バブル、フィルター、シャドウなど | ○ | ○ | ○ | ●(5 エフェクト) | +| **イージング** | | | | | +| Quad | ○ | ● | ● | ● | +| Back、Bounce、Circ、Cubic、Elastic、Expo、Gaussian、Linear、Quart、Quint、Sigmoid、Sine、Smoothstep | ○ | ○ | ○ | ● | +| **カラープラグイン** | | | | | +| HEX、HSL、RGB | ● | ● | ● | ● | +| HSV、HWB、LAB、LCH、Named、OKLAB、OKLCH | ○ | ○ | ○ | ● | + +### 専用 API バンドル + +| 機能 | confetti | fireworks | particles | ribbons | +| ---------------- | -------------------------------------------------- | ------------------------- | ----------------- | ------------------ | +| 形状 | 円、ハート、カード、絵文字、画像、多角形、四角、星 | 線 | (basic から) | リボン | +| インタラクション | — | — | リンク + 衝突 | — | +| 特殊プラグイン | エミッター、motion | エミッター、sounds、blend | — | エミッター、motion | +| API 呼び出し | `confetti(opts)` | `fireworks(opts)` | `particles(opts)` | `ribbons(opts)` | + +## 選択ガイド + +```mermaid +flowchart TD + A[素早く始めたい?] -->|はい| B[プリセットを使う?] + A -->|いいえ| C[バンドルサイズは?] + B -->|はい| D["@tsparticles/configs + @tsparticles/slim"] + B -->|いいえ| E["紙吹雪? → @tsparticles/confetti"] + B -->|いいえ| F["花火? → @tsparticles/fireworks"] + B -->|いいえ| G["パーティクル背景? → @tsparticles/particles"] + B -->|いいえ| H["リボン? → @tsparticles/ribbons"] + C -->|"最小(円のみ)"| I["@tsparticles/basic"] + C -->|"中程度(形状 + インタラクション)"| J["@tsparticles/slim"] + C -->|"最大(全機能)"| K["tsparticles(loadFull)"] + C -->|"リポジトリ全体"| L["@tsparticles/all"] ``` -CDN リンクや他の package manager の例が必要な場合: - -- [`/guide/installation`](/ja/guide/installation) を参照してください。 - -## セットアップ例 - -### engine + loader bundles (`basic`, `slim`, `full`, `all`) - -```ts -import { tsParticles } from "@tsparticles/engine"; -import { loadSlim } from "@tsparticles/slim"; - -await loadSlim(tsParticles); - -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - number: { value: 80 }, - move: { enable: true, speed: 2 }, - }, - }, -}); +**経験則:** + +1. ほとんどのプロジェクトは `@tsparticles/slim` から始めます。 +2. バンドルサイズが重要で円のみ必要な場合: `@tsparticles/basic`。 +3. エミッター、アブソーバー、テキスト、ウィブル/ティルト/ロールが必要な場合: `tsparticles` で `loadFull`。 +4. 全機能を使った迅速なプロトタイピング: `@tsparticles/all`。 +5. 最小セットアップで目的別エフェクト(紙吹雪、花火、パーティクル背景、リボン): 専用 API バンドル。 + +## クイックインストール + +| バンドル | npm コマンド | ローダー関数 | CDN URL | +| ------------------------ | ------------------------------------------------- | ------------------------ | -------------------------------------------------------------- | +| `@tsparticles/basic` | `pnpm add @tsparticles/engine @tsparticles/basic` | `loadBasic(tsParticles)` | `@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| `@tsparticles/slim` | `pnpm add @tsparticles/engine @tsparticles/slim` | `loadSlim(tsParticles)` | `@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| `tsparticles`(full) | `pnpm add @tsparticles/engine tsparticles` | `loadFull(tsParticles)` | `tsparticles@4/tsparticles.bundle.min.js` | +| `@tsparticles/all` | `pnpm add @tsparticles/engine @tsparticles/all` | `loadAll(tsParticles)` | `@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| `@tsparticles/confetti` | `pnpm add @tsparticles/confetti` | `confetti(opts)` | `@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| `@tsparticles/fireworks` | `pnpm add @tsparticles/fireworks` | `fireworks(opts)` | `@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| `@tsparticles/particles` | `pnpm add @tsparticles/particles` | `particles(opts)` | `@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| `@tsparticles/ribbons` | `pnpm add @tsparticles/ribbons` | `ribbons(opts)` | `@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | + +**注意:** basic/slim/full/all バンドルでは、`tsParticles.load()` の前に `load*` を呼び出す必要があります。CDN ファイルはローダー関数をグローバルに公開しますが、自動実行はしません。confetti/fireworks/particles/ribbons バンドルは自己完結型 API を持ち、`confetti()`、`fireworks()` などを直接呼び出します。 + +`@tsparticles/slim` の CDN 例: + +```html + + + ``` -他の preset を使う場合は、loader の import/関数名だけ差し替えます: +`@tsparticles/confetti` の CDN 例: -- `@tsparticles/basic` -> `loadBasic` -- `tsparticles` -> `loadFull` -- `@tsparticles/all` -> `loadAll` - -### 特化 API (`confetti`, `fireworks`, `particles`, `ribbons`) - -```ts -import { confetti } from "@tsparticles/confetti"; -import { fireworks } from "@tsparticles/fireworks"; -import { particles } from "@tsparticles/particles"; -import { ribbons } from "@tsparticles/ribbons"; - -await confetti({ count: 80, spread: 60 }); -await fireworks({ sounds: false }); -await particles({ count: 100, links: true }); -await ribbons({ count: 5, spread: 0 }); +```html + + ``` -これらの API は、多数の engine plugin を手動接続せずに素早く統合したい場合に最適です。 - -## 実践的な選び方 - -1. ほとんどのプロジェクトでは `@tsparticles/slim` から開始する。 -2. bundle サイズ最優先で機能要件がシンプルなら `@tsparticles/basic` を使う。 -3. 幅広い機能を持つ full な土台を `loadFull` で使いたい場合は `tsparticles` を使う。 -4. プロトタイピングや、多くの機能をすぐ使いたい場合は `@tsparticles/all` を使う。 -5. UI に特化した 1 つの演出を最小セットアップで入れたい場合は `@tsparticles/confetti`、`@tsparticles/fireworks`、`@tsparticles/particles`、`@tsparticles/ribbons` を使う。 +インストールの詳細は[インストールガイド](/ja/guide/installation)を参照してください。 ## 関連ページ -- playground の特化 bundles: [`/playground/bundles`](/ja/playground/bundles) -- スタートガイド: [`/guide/getting-started`](/ja/guide/getting-started) -- インストール一覧: [`/guide/installation`](/ja/guide/installation) -- wrappers 概要: [`/guide/wrappers`](/ja/guide/wrappers) +- [はじめに](/ja/guide/getting-started) +- [インストールガイド](/ja/guide/installation) +- [プリセットカタログ](/ja/demos/presets) +- [パレットカタログ](/ja/demos/palettes) +- [形状カタログ](/ja/demos/shapes) diff --git a/websites/website/docs/ja/guide/color-formats.md b/websites/website/docs/ja/guide/color-formats.md index cc665e4aa59..d19e834c96f 100644 --- a/websites/website/docs/ja/guide/color-formats.md +++ b/websites/website/docs/ja/guide/color-formats.md @@ -1,6 +1,6 @@ # カラーフォーマット -tsParticles は、`background`、`particles.color`、プラグイン設定などのオプションにわたって複数のカラー形式を受け入れます。 +tsParticles は、`background`、`particles.paint`、プラグイン設定などのオプションにわたって複数のカラー形式を受け入れます。 ## 一般的な形式 diff --git a/websites/website/docs/ja/guide/getting-started.md b/websites/website/docs/ja/guide/getting-started.md index 2bb60c754ac..5f02caec804 100644 --- a/websites/website/docs/ja/guide/getting-started.md +++ b/websites/website/docs/ja/guide/getting-started.md @@ -1,106 +1,197 @@ # はじめに -このパスは、2026 年の `tsParticles` に対する最も迅速で信頼性の高いセットアップです。 +tsParticles は、パーティクルアニメーション、紙吹雪、花火などを生成するための JavaScript/TypeScript ライブラリです。最新のブラウザで動作し、npm パッケージとしても CDN の ` + + + + +
+ + + +``` + +> **注意**: CDN バンドルでも、`tsParticles.load()` の前に `loadSlim(tsParticles)`(または `loadBasic` / `loadFull` / `loadAll`)を呼び出す必要があります。CDN バンドルはローダー関数をグローバルに公開しますが、自動実行はしません。 + +`@tsparticles/basic` → `loadBasic`、`tsparticles` → `loadFull`、`@tsparticles/all` → `loadAll` も同様のパターンです。 + +### パス C — 専用 API を持つ特化バンドル(confetti、fireworks、particles) + +一部のバンドルは独自の簡略化 API を持ち、`tsParticles.load()` を使用する必要はありません: + +```html + + + + + + + + + +``` + +`fireworks()`、`particles()`、`ribbons()` も同様です。 -- `@tsparticles/slim`: ほとんどのアプリはここから開始する必要があります。 -- `@tsparticles/basic`: 非常に軽いセットアップ向けの小さな機能セット。 -- `@tsparticles/all`: すべてが含まれており、迅速なプロトタイピングが容易です。 +## どのバンドルを選ぶべきか -直接の `tsParticles` セットアップではなく、集中的な API が必要な場合: +| バンドル | npm | 使用すべきケース | +| ------------------------ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------- | +| `@tsparticles/basic` | `loadBasic(tsParticles)` | 最小構成: 円、移動、不透明度、サイズ。インタラクションなし。 | +| `@tsparticles/slim` | `loadSlim(tsParticles)` | **ほとんどのプロジェクトに推奨。** クリック/ホバー操作、リンク、画像、星、多角形を追加。 | +| `tsparticles` | `loadFull(tsParticles)` | 公式機能をフルセット: エミッター、アブソーバー、テキスト形状、ロール、ウィブル、トレイル。 | +| `@tsparticles/all` | `loadAll(tsParticles)` | **リポジトリのすべて:** あらゆる形状、インタラクション、エフェクト、イージング、パス、エクスポート。プロトタイピング専用。 | +| `@tsparticles/confetti` | `confetti(options)` | 1 関数呼び出しで紙吹雪。専用 API。 | +| `@tsparticles/fireworks` | `fireworks(options)` | 1 関数呼び出しで花火。専用 API。 | +| `@tsparticles/particles` | `particles(options)` | 簡略化されたパーティクル背景。専用 API。 | +| `@tsparticles/ribbons` | `ribbons(options)` | リボンエフェクト。専用 API。 | -- `@tsparticles/particles`: 簡素化されたパーティクル バックグラウンド API -- `@tsparticles/confetti`: 1 回の呼び出しで使える紙吹雪 API -- `@tsparticles/fireworks`: 1 回の呼び出しで使える花火 API +詳細: [`/ja/guide/bundles`](/ja/guide/bundles)。 -## 5) 速度が必要な場合はプリセット/構成を使用します +## プリセットの使用 -事前に構築されたエフェクトを希望する場合: +`@tsparticles/configs` パッケージには、数十種類の既成設定(アブソーバー、バブル、雪、星、重力、衝突など)が含まれています。 ```bash -pnpm add @tsparticles/configs +pnpm add @tsparticles/engine @tsparticles/slim @tsparticles/configs +``` + +```ts +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import "@tsparticles/configs"; + +await loadSlim(tsParticles); + +await tsParticles.load({ + id: "tsparticles", + options: { preset: "snow" }, +}); ``` -次に、[`demo/vite` アプリ](https://github.com/tsparticles/tsparticles/blob/main/demo/vite/src/main.ts) のように、キーによって 1 つの構成を読み込みます。 +CDN の場合: -プリセット名ベースのセットアップを希望する場合は、[`/demos/presets`](/ja/demos/presets) の公式プリセット カタログを使用してください。 +```html + + + + +``` -## クイックドキュメントマップ +## クイックリファレンス -- ルートオプション: [`/options/`](/ja/options/) -- ラッパーリファレンス: [`/guide/wrappers`](/ja/guide/wrappers) -- プリセットカタログ: [`/demos/presets`](/ja/demos/presets) -- パレット カタログ: [`/demos/palettes`](/ja/demos/palettes) -- シェイプ カタログ: [`/demos/shapes`](/ja/demos/shapes) -- particles.js からの移行: [`/migrations/particles-js`](/ja/migrations/particles-js) -- カラー形式: [`/guide/color-formats`](/ja/guide/color-formats) -- コンテナのライフサイクル: [`/guide/container-lifecycle`](/ja/guide/container-lifecycle) -- プラグインとカスタマイズ: [`/guide/plugins-customization`](/ja/guide/plugins-customization) +- オプションのドキュメント: [`/ja/options/`](/ja/options/) +- バンドルガイド: [`/ja/guide/bundles`](/ja/guide/bundles) +- プリセットカタログ: [`/ja/demos/presets`](/ja/demos/presets) +- パレットカタログ: [`/ja/demos/palettes`](/ja/demos/palettes) +- 形状カタログ: [`/ja/demos/shapes`](/ja/demos/shapes) +- フレームワークラッパー: [`/ja/guide/wrappers`](/ja/guide/wrappers) +- カラー形式: [`/ja/guide/color-formats`](/ja/guide/color-formats) +- コンテナライフサイクル: [`/ja/guide/container-lifecycle`](/ja/guide/container-lifecycle) +- プラグインとカスタマイズ: [`/ja/guide/plugins-customization`](/ja/guide/plugins-customization) ## トラブルシューティング -- 空白の画面: `tsParticles.load` を呼び出す前に、`#tsparticles` が存在することを確認してください。 -- 不足している機能: 別のプラグイン/パッケージ (形状、インタラクション、アップデーター) が必要になる可能性があります。 -- オプションの入力エラー: パッケージを同じメジャー/マイナー バージョンに合わせてください。 +| 問題 | 原因 | 解決策 | +| ------------------------------------------------------ | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | +| 画面が真っ白、パーティクルなし | `tsParticles.load()` 呼び出し時に `#tsparticles` が DOM に存在しない | DIV がスクリプトの前に存在することを確認するか、`DOMContentLoaded` を使用 | +| 画面が真っ白、パーティクルなし | `@tsparticles/engine` のみインストールしている | バンドル(`@tsparticles/slim`)またはプラグインもインストールする — エンジン単体では描画する形状がない | +| "loadBasic/loadSlim/loadFull is not a function" エラー | バンドルがインストールされていない、またはインポートが間違っている | `pnpm add @tsparticles/slim` して `{ loadSlim }` をインポート | +| パーティクルが動かない | `move.enable` が `true` になっていない | `move: { enable: true, speed: 2 }` を追加 | +| 機能(リンク、衝突など)がない | 選択したバンドルに含まれていない | よりリッチなバンドル(`@tsparticles/slim` または `tsparticles`)に切り替えるか、特定のプラグインをインストール | +| TypeScript の型エラー | パッケージバージョンの不一致 | エンジンとバンドルを同じメジャー/マイナーバージョンに揃える | diff --git a/websites/website/docs/ja/guide/installation.md b/websites/website/docs/ja/guide/installation.md index 9a9738c8a0d..11ed8ea15ce 100644 --- a/websites/website/docs/ja/guide/installation.md +++ b/websites/website/docs/ja/guide/installation.md @@ -1,109 +1,146 @@ # インストール -このページは `tsParticles` メイン README のインストールマトリクスを反映しています。 +## パスの選択 -公式リファレンス: +| シナリオ | コマンド | +| ------------------------ | ------------------------------------------------- | +| クイックスタート(推奨) | `pnpm add @tsparticles/engine @tsparticles/slim` | +| 最小構成 | `pnpm add @tsparticles/engine @tsparticles/basic` | +| フル機能 | `pnpm add @tsparticles/engine tsparticles` | +| リポジトリのすべて | `pnpm add @tsparticles/engine @tsparticles/all` | +| 紙吹雪のみ | `pnpm add @tsparticles/confetti` | +| 花火のみ | `pnpm add @tsparticles/fireworks` | +| パーティクル背景 | `pnpm add @tsparticles/particles` | +| リボンエフェクト | `pnpm add @tsparticles/ribbons` | -## 導入パスを選ぶ +> **重要**: `@tsparticles/engine` 単体では何も描画しません。必ずバンドル(形状とアニメーションを読み込むため)または個別のプラグインを追加してください。[バンドルガイド](/ja/guide/bundles)を参照してください。 -- **高速デフォルト**: `@tsparticles/engine` + `@tsparticles/slim` -- **より軽いカスタム runtime**: `@tsparticles/engine` + 必要な plugins のみ -- **用途別 API**: `@tsparticles/particles`、`@tsparticles/confetti`、`@tsparticles/fireworks`、`@tsparticles/ribbons` -- **全機能入り**: `@tsparticles/all` +## npm -## ホスティング / CDN - -以下のプロバイダーを利用できます(またはビルド済みファイルを self-host)。 - -### jsDelivr - -- -- -- -- -- -- -- -- - -### cdnjs +```bash +# engine + slim(ほとんどのプロジェクトに推奨) +npm install @tsparticles/engine @tsparticles/slim -- +# engine + basic(最小) +npm install @tsparticles/engine @tsparticles/basic -### unpkg +# engine + full(tsparticles) +npm install @tsparticles/engine tsparticles -- -- -- -- -- -- -- -- +# engine + all +npm install @tsparticles/engine @tsparticles/all -## package manager でインストール +# 専用 API バンドル(明示的な engine は不要) +npm install @tsparticles/confetti +npm install @tsparticles/fireworks +npm install @tsparticles/particles +npm install @tsparticles/ribbons +``` -### npm +## yarn ```bash -npm install @tsparticles/engine +yarn add @tsparticles/engine @tsparticles/slim +# ... 他のバンドルも同様のパターン ``` -### yarn +## pnpm ```bash -yarn add @tsparticles/engine +pnpm add @tsparticles/engine @tsparticles/slim +# ... 他のバンドルも同様のパターン ``` -### pnpm +## CDN(script タグ) -```bash -pnpm add @tsparticles/engine -``` +すべてのパッケージは jsDelivr、unpkg、cdnjs で利用可能です。 -## import と require +### jsDelivr -```ts -const tsParticles = require("@tsparticles/engine"); +| バンドル | URL | +| --------------------- | ------------------------------------------------------------------------------------------- | +| Engine | `https://cdn.jsdelivr.net/npm/@tsparticles/engine@4/tsparticles.engine.min.js` | +| Basic | `https://cdn.jsdelivr.net/npm/@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| Slim | `https://cdn.jsdelivr.net/npm/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| Full(`tsparticles`) | `https://cdn.jsdelivr.net/npm/tsparticles@4/tsparticles.bundle.min.js` | +| All | `https://cdn.jsdelivr.net/npm/@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| Confetti | `https://cdn.jsdelivr.net/npm/@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| Fireworks | `https://cdn.jsdelivr.net/npm/@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| Particles | `https://cdn.jsdelivr.net/npm/@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| Ribbons | `https://cdn.jsdelivr.net/npm/@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | +| particles.js 互換 | `https://cdn.jsdelivr.net/npm/@tsparticles/pjs@4/tsparticles.pjs.min.js` | -// or +### unpkg -import { tsParticles } from "@tsparticles/engine"; -``` +同じ構造: `https://unpkg.com/{package-name}@{version}/{filename}` -## 最小 runtime セットアップ(`@tsparticles/slim`) +例: +`https://unpkg.com/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` + +### cdnjs + +`https://cdnjs.com/libraries/tsparticles` + +## インポート例 + +### バンドラー使用(ES module インポート) ```ts +// Engine + バンドルローダー import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; await loadSlim(tsParticles); +await tsParticles.load({ id: "tsparticles", options: { ... } }); +``` -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - move: { - enable: true, - }, - number: { - value: 60, - }, - }, - }, -}); +### CommonJS(require) + +```ts +const { tsParticles } = require("@tsparticles/engine"); +const { loadSlim } = require("@tsparticles/slim"); + +(async () => { + await loadSlim(tsParticles); + await tsParticles.load({ id: "tsparticles", options: { ... } }); +})(); ``` -## 関連ページ +### CDN(script タグ) + +```html + + + + + + +``` -- [`/guide/getting-started`](/ja/guide/getting-started) -- [`/guide/wrappers`](/ja/guide/wrappers) -- [`/demos/presets`](/ja/demos/presets) -- [`/migrations/particles-js`](/ja/migrations/particles-js) +専用 API バンドルの場合: -## legacy 互換 +```html + + +``` -既存の particles.js 統合を移行する場合は、互換パッケージを利用してください。 +## 関連ページ -- npm: -- jsDelivr: +- [はじめに](/ja/guide/getting-started) +- [バンドルガイド](/ja/guide/bundles) +- [フレームワークラッパー](/ja/guide/wrappers) diff --git a/websites/website/docs/ja/guides/angular.md b/websites/website/docs/ja/guides/angular.md new file mode 100644 index 00000000000..0d85bbea8cc --- /dev/null +++ b/websites/website/docs/ja/guides/angular.md @@ -0,0 +1,631 @@ +--- +title: Angular インテグレーション +description: "@tsparticles/angular を使用して tsParticles を Angular アプリケーションに統合するためのステップバイステップガイド。" +--- + +# Angular インテグレーション + +`@tsparticles/angular` パッケージは、tsParticles の Angular コンポーネント、モジュール、およびサービスを提供します。このガイドでは、従来の `NgModule` アプローチと Angular 17+ のスタンドアロンコンポーネントの両方をカバーします。 + +--- + +## インストール + +```bash +npm install @tsparticles/angular @tsparticles/engine +``` + +すべての機能が必要な場合は、完全なバンドルをインストールしてください: + +```bash +npm install tsparticles +``` + +オプションのプリセットパッケージ: + +```bash +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +``` + +--- + +## 基本的な使い方 (NgModule) + +### 1. モジュールのインポート + +```typescript +import { NgModule } from "@angular/core"; +import { BrowserModule } from "@angular/platform-browser"; +import { NgParticlesModule } from "@tsparticles/angular"; +import { AppComponent } from "./app.component"; + +@NgModule({ + declarations: [AppComponent], + imports: [BrowserModule, NgParticlesModule], + bootstrap: [AppComponent], +}) +export class AppModule {} +``` + +### 2. エンジンの初期化 + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d47a1", + }, + fpsLimit: 120, + particles: { + number: { + value: 80, + }, + color: { + value: "#ffffff", + }, + shape: { + type: "circle", + }, + opacity: { + value: 0.5, + }, + size: { + value: { min: 1, max: 5 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Particles container loaded", container); + } +} +``` + +### 3. テンプレート + +```html + +``` + +--- + +## エンジン初期化の詳細 + +`NgParticlesService.init()` メソッドは、通常 `AppComponent.ngOnInit()` で1回だけ呼び出す必要があります。アプリケーションが必要とするプラグイン/プリセットをロードするコールバックを受け取ります。 + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesService } from "@tsparticles/angular"; +import type { Engine } from "@tsparticles/engine"; + +@Component({ ... }) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + // バンドルを小さくするために必要なものだけをロード + await loadBasic(engine); // 基本シェイプ + 移動 + await loadEmittersPlugin(engine); // エミッターシェイプ + }); + } +} +``` + +`tsparticles` から利用可能なローダー関数: + +| 関数 | 説明 | +| ------------------- | ------------------------------------------------ | +| `loadFull(engine)` | すべての機能(最大のバンドル) | +| `loadBasic(engine)` | コアシェイプ(円、四角、多角形など) | +| `loadSlim(engine)` | ほとんどの機能からレアに使われるプラグインを除外 | +| `loadAll(engine)` | `loadFull` の非推奨エイリアス | + +--- + +## クラッカーエフェクト + +```bash +npm install @tsparticles/preset-confetti +``` + +```typescript +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// NgParticlesService.init コールバック内: +await loadConfettiPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "confetti", + background: { + color: "transparent", + }, +}; +``` + +または、便利な `` コンポーネントを使用: + +```typescript +// app.module.ts +import { NgParticlesModule } from "@tsparticles/angular"; + +@NgModule({ + imports: [NgParticlesModule], +}) +export class AppModule {} +``` + +```html + +``` + +--- + +## 花火エフェクト + +```bash +npm install @tsparticles/preset-fireworks +``` + +```typescript +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; + +// NgParticlesService.init コールバック内: +await loadFireworksPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "fireworks", + background: { + color: "#000000", + }, +}; +``` + +または、`` コンポーネントを使用: + +```html + +``` + +> 花火の自動開始は避けてください。不要なリソース使用を防ぐため、ユーザーアクション(クリック、スクロール)にバインドしてください。 + +--- + +## カスタムパーティクル設定 + +インタラクティビティを備えた本格的なカスタムパーティクル設定: + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-particles", + templateUrl: "./particles.component.html", +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d0d0d", + }, + fpsLimit: 60, + particles: { + number: { + value: 100, + density: { + enable: true, + }, + }, + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + shape: { + type: ["circle", "square", "triangle"], + }, + opacity: { + value: 0.8, + random: true, + anim: { + enable: true, + speed: 1, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + random: true, + anim: { + enable: true, + speed: 4, + size_min: 1, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.3, + width: 1, + triangles: { + enable: true, + color: "#ffffff", + opacity: 0.05, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { + enable: true, + rotateX: 600, + rotateY: 600, + }, + }, + life: { + duration: { + value: 5, + random: true, + }, + count: 0, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: { + enable: true, + }, + }, + modes: { + grab: { + distance: 200, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + detectRetina: true, + }; + + particlesLoaded(container: Container): void { + console.log("Container loaded", container); + } +} +``` + +```html + +``` + +--- + +## イベント + +`ngx-particles` コンポーネントは `particlesLoaded` イベントを発行します: + +```typescript +import type { Container } from "@tsparticles/engine"; + +// コンポーネントのメソッド +onParticlesLoaded(container: Container): void { + // コンテナ API へのアクセス + container.pause(); + container.play(); + container.destroy(); + container.exportImage().then((blob) => { /* ... */ }); +} +``` + +```html + +``` + +コンテナ参照により、一時停止、再開、破棄、エクスポートなど、完全なプログラム制御が可能になります。 + +--- + +## テンプレート構文と条件付きレンダリング + +Angular の構造ディレクティブを使用してコンポーネントを切り替えます: + +```html + + + +``` + +```typescript +export class AppComponent { + showParticles = true; + // ... +} +``` + +`*ngIf` が `false` と評価されると、コンポーネント(キャンバスとすべてのパーティクルインスタンスを含む)が破棄されます。再作成すると、すべてが最初から再初期化されます。 + +--- + +## スタンドアロンコンポーネント (Angular 17+) + +Angular 17+ では、スタンドアロンコンポーネントに `NgParticlesModule` を直接インポートできます: + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesModule, NgParticlesService } from "@tsparticles/angular"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +@Component({ + selector: "app-particles", + standalone: true, + imports: [NgParticlesModule], + template: ` + + `, +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 50 }, + color: { value: "#fff" }, + shape: { type: "circle" }, + move: { enable: true, speed: 2 }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Loaded", container); + } +} +``` + +`NgModule` ラッパーは不要です — コンポーネントの `imports` 配列に `NgParticlesModule` をインポートするだけです。 + +--- + +## 完全なコンポーネント例 + +### app.component.ts + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + title = "tsParticles Angular Demo"; + + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadSlim(engine); + }); + } + + particlesOptions: ISourceOptions = { + autoPlay: true, + background: { + color: "#1e1e2e", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMask: { + cover: { + color: "#1e1e2e", + }, + enable: false, + }, + fullScreen: { + enable: true, + zIndex: -1, + }, + detectRetina: true, + fpsLimit: 60, + particles: { + color: { + value: "#cdd6f4", + }, + links: { + color: "#cdd6f4", + distance: 150, + enable: true, + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1, + }, + number: { + value: 60, + }, + opacity: { + value: 0.6, + }, + size: { + value: { min: 1, max: 3 }, + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Particles loaded", container); + } +} +``` + +### app.component.html + +```html +
+ + +
+

{{ title }}

+

Particles are running in the background.

+
+
+``` + +### app.component.css + +```css +:host { + display: block; + width: 100%; + height: 100%; +} +``` + +--- + +## API リファレンス + +| コンポーネント | セレクタ | 説明 | +| -------------- | --------------- | ---------------------------------------- | +| Particles | `ngx-particles` | 完全なパーティクルシステムコンポーネント | +| Confetti | `ngx-confetti` | プリ設定されたクラッカーエフェクト | +| Fireworks | `ngx-fireworks` | プリ設定された花火エフェクト | + +### `ngx-particles` 入力 + +| 入力 | タイプ | デフォルト | 説明 | +| --------- | ---------------- | --------------- | ---------------------- | +| `id` | `string` | `"tsparticles"` | キャンバス要素 ID | +| `options` | `ISourceOptions` | `{}` | パーティクル設定 | +| `url` | `string` | — | リモート JSON 設定 URL | + +### `ngx-particles` 出力 + +| 出力 | ペイロード | 説明 | +| ----------------- | ----------- | ---------------------------------------- | +| `particlesLoaded` | `Container` | コンテナが初期化されたときに発行されます | + +--- + +## トラブルシューティング + +- **空白/表示されないキャンバス** — 親要素に定義された高さがあることを確認してください(例: `height: 100vh`)。キャンバスはコンテナの寸法を継承します。 +- **`NgParticlesService.init()` が複数回呼ばれた場合** — 1回だけ呼び出してください。通常は `AppComponent.ngOnInit()` で行います。後続の呼び出しは安全ですが冗長です。 +- **モジュールが見つからない** — `@tsparticles/angular` が `package.json` の依存関係にリストされ、`NgParticlesModule` をインポートしていることを確認してください。 +- **`NullInjectorError: No provider for NgParticlesService`** — コンポーネントを提供するモジュールで `NgParticlesModule` をインポート(または再エクスポート)する必要があります。 diff --git a/websites/website/docs/ja/guides/astro.md b/websites/website/docs/ja/guides/astro.md new file mode 100644 index 00000000000..3c2f55de335 --- /dev/null +++ b/websites/website/docs/ja/guides/astro.md @@ -0,0 +1,384 @@ +# Astro インテグレーション + +公式の `@tsparticles/astro` 統合パッケージを使用して、Astro サイトで tsParticles を使用します。 + +## インストール + +パッケージマネージャーを使用して、Astro 統合パッケージと tsParticles コアをインストールします: + +```bash +npm install @tsparticles/astro tsparticles +``` + +```bash +pnpm add @tsparticles/astro tsparticles +``` + +```bash +yarn add @tsparticles/astro tsparticles +``` + +## エンジンの初期化 + +tsParticles はモジュラーアーキテクチャを採用しています。パーティクルをレンダリングする前に、必要な機能でエンジンを初期化する必要があります。クライアントスクリプト(例: `src/scripts/particles-init.ts`)を作成するか、Astro コンポーネント内でインライン ` +``` + +> `id` プロップは、基礎となるキャンバスコンテナの `
` に渡されます。スタイリングや `document.getElementById()` を介した命令的なアクセスに使用します。 + +## TypeScript サポート + +この統合パッケージは完全な TypeScript 宣言を提供します。`@tsparticles/engine` の `ISourceOptions` を使用して設定を型付けします: + +```typescript +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { + value: 50, + density: { enable: true }, + }, + opacity: { value: 0.5 }, + shape: { type: "circle" }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + repulse: { distance: 200 }, + }, + }, +}; +``` + +## カスタム設定 + +以下は、任意の Astro ページにドロップインできる、より詳細な設定です: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + autoPlay: true, + background: { + color: "#0d47a1", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMode: { + enable: true, + zIndex: -1, + }, + fpsLimit: 120, + particles: { + color: { + value: "#ffffff", + animation: { + enable: true, + speed: 20, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + triangles: { + enable: true, + opacity: 0.1, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "out", + attract: { enable: false }, + }, + number: { + value: 80, + density: { + enable: true, + }, + }, + opacity: { + value: 0.5, + animation: { + enable: true, + speed: 1, + sync: false, + }, + }, + shape: { + type: "circle", + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 3, + sync: false, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: true, + }, + modes: { + grab: { + distance: 200, + links: { opacity: 0.5 }, + }, + push: { quantity: 4 }, + }, + }, + detectRetina: true, +}; +--- + + + + +``` + +## プリセットの使用 + +手動で設定を構築する代わりに、エンジン初期化時にプリセットをロードし、オプションでそれを参照します: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + preset: "stars", + background: { color: "#000000" }, +}; +--- + + + + +``` + +## 他のフレームワークとの統合 + +Astro は React、Vue、Svelte、Solid などの UI フレームワークをサポートしているため、`.astro` ファイル内でフレームワーク固有の tsParticles コンポーネントを使用できます: + +### Astro で React を使用 + +```astro +--- +import Particles from "@tsparticles/react"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +### Astro で Vue を使用 + +```astro +--- +import Particles from "@tsparticles/vue3"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +> `client:load` ディレクティブは、Astro にページ読み込み時にコンポーネントを即座にハイドレートするように指示します。遅延読み込みには `client:visible` を使用します。 + +## 完全なページ例 + +パーティクルがアニメーション背景として機能する完全な Astro ページ: + +```astro +--- +import Layout from "../layouts/Layout.astro"; +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + number: { value: 100 }, + color: { value: "#ffffff" }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + size: { + value: { min: 1, max: 4 }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, +}; +--- + + +
+

Welcome

+

This page has a particle background powered by tsParticles.

+
+ +
+ + + + +``` + +## コンポーネントプロップ + +| プロップ | タイプ | デフォルト | 説明 | +| -------------------- | ---------------- | ------------------------- | --------------------------------------------- | +| `id` | `string` | `"tsparticles"` | コンテナの DOM 要素 ID | +| `options` | `ISourceOptions` | `{}` | 完全な tsParticles 設定オブジェクト | +| `url` | `string` | — | リモート JSON URL から設定をロード | +| `particlesClassName` | `string` | `"tsparticles-canvas-el"` | キャンバス要素の CSS クラス | +| `container` | `object` | — | 既存の `Container` インスタンス(上級者向け) | diff --git a/websites/website/docs/ja/guides/ember.md b/websites/website/docs/ja/guides/ember.md new file mode 100644 index 00000000000..a5764632b80 --- /dev/null +++ b/websites/website/docs/ja/guides/ember.md @@ -0,0 +1,346 @@ +--- +title: Ember ガイド +description: tsParticles を Ember.js アプリケーションに統合するための完全ガイド。 +--- + +# Ember ガイド + +## 目次 + +1. [インストール](#installation) +2. [エンジンの初期化](#engine-initialization) +3. [基本的な使い方](#basic-usage) +4. [カスタム設定](#custom-configuration) +5. [イベント処理](#event-handling) +6. [条件付きレンダリング](#conditional-rendering) +7. [TypeScript の例](#typescript-example) + +--- + +## インストール + +ember-cli を使用して Ember アドオンと tsParticles エンジンをインストールします: + +```bash +ember install @tsparticles/ember +``` + +これにより、アドオンとそのピア依存関係である `tsparticles` がインストールされます。オプションでプリセットパッケージを追加できます: + +```bash +npm install @tsparticles/slim +``` + +--- + +## エンジンの初期化 + +このアドオンは、アプリケーションレベルで1回呼び出す `initParticlesEngine` ユーティリティをエクスポートします。アプリが必要とする機能、プリセット、またはシェイプをロードする非同期コールバックを受け取ります。 + +```typescript +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadFull } from "tsparticles"; + +// アプリケーションブートストラップ時にこれを呼び出す +if (typeof window !== "undefined") { + void initParticlesEngine(async (engine) => { + await loadFull(engine); + }); +} +``` + +この呼び出しの典型的な場所は、アプリケーションルートの `beforeModel` フック、アプリケーションコントローラーのコンストラクター、またはインスタンス初期化子です。エンジンシングルトンは1回初期化され、アプリ内のすべての `` コンポーネント間で共有されます。 + +--- + +## 基本的な使い方 + +エンジンを初期化した後、任意のテンプレートで `` コンポーネントを使用します。パーティクル設定は `@options` 引数で渡します。 + +```hbs +{{! app/templates/application.hbs }} + + +``` + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, + }; +} +``` + +--- + +## カスタム設定 + +インタラクティビティ、複数のシェイプタイプ、レスポンシブ密度を備えた、よりリッチな設定を構築します。 + +```typescript +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class IndexController extends Controller { + options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, + }; +} +``` + +```hbs + +``` + +--- + +## イベント処理 + +`` コンポーネントは、コンテナの初期化が完了し、最初のフレームがレンダリングされたときに `@particlesLoaded` アクションを発生させます。これを使用して、プログラム制御のために `Container` インスタンスにアクセスします。 + +```typescript +import Controller from "@ember/controller"; +import { action } from "@ember/object"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + /* ... */ + }; + + @action + loadedCallback(container: Container) { + console.log("Particles loaded", container.id); + + // プログラム制御の例: + setTimeout(() => { + container.pause(); + console.log("Particles paused after 5 seconds"); + }, 5000); + } +} +``` + +```hbs + +``` + +個別のアクションを定義したくない場合は、テンプレートヘルパーを使用してインラインでコールバックパターンを使用することもできます。 + +--- + +## 条件付きレンダリング + +Ember の `{{if}}` ヘルパーを `@tracked` プロパティと組み合わせて使用し、`` コンポーネントがレンダリングされるタイミングを制御します。これは、エンジンの初期化が非同期であり、エンジンの準備ができる前にコンポーネントがレンダリングされるのを防ぎたい場合に便利です。 + +```typescript +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked engineReady = false; + + options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { enable: true, speed: 1, outModes: { default: "bounce" } }, + }, + background: { color: "#1a1a2e" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } +} +``` + +```hbs +{{#if this.engineReady}} + +{{else}} +

Loading particles...

+{{/if}} +``` + +`@tracked` デコレーターにより、プロミスが解決されるとテンプレートが自動的に再レンダリングされます。 + +--- + +## TypeScript の例 + +以下は、スリムプリセット、インタラクティビティ、およびライフサイクル管理を使用した完全な統合パターンを示す、型付けされた完全な Ember アプリケーションコントローラーです。 + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked private engineReady = false; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } + + @action + private handleParticlesLoaded(container: Container): void { + this.container = container; + console.log("Particles loaded in container:", container.id); + } +} +``` + +```hbs +{{! app/templates/application.hbs }} + +{{#if this.engineReady}} +
+

tsParticles + Ember

+ +
+{{else}} +
+

Initializing particle engine...

+
+{{/if}} +``` + +--- + +これで、tsParticles を Ember.js アプリケーションに統合するために必要なすべてが揃いました。各例は自己完結型で、プロジェクトにコピーしてすぐに使用できます。 diff --git a/websites/website/docs/ja/guides/index.md b/websites/website/docs/ja/guides/index.md new file mode 100644 index 00000000000..ab18e20c7e5 --- /dev/null +++ b/websites/website/docs/ja/guides/index.md @@ -0,0 +1,58 @@ +--- +title: ステップバイステップガイド +description: tsParticles をプロジェクトに統合するためのフレームワーク別ガイドをご覧ください。 +--- + +# ステップバイステップガイド + +tsParticles ガイドセクションへようこそ。Vanilla JS の静的サイト、React や Vue のシングルページアプリケーション、Next.js や Nuxt のフルスタックアプリケーションのいずれを構築する場合でも、これらのステップバイステップチュートリアルでインストール、基本的な使い方、高度な設定、インタラクティブエフェクトを順を追って説明します。 + +各ガイドは自己完結型で、すぐに始められるコピー&ペースト可能なコード例が含まれています。 + +## 利用可能なガイド + +| フレームワーク / ラッパー | パッケージ | 説明 | +| --------------------------------- | -------------------------------------------- | ------------------------------------------------------------ | +| [Vanilla JS](./vanilla) | `tsparticles`(CDN または npm) | `tsParticles.load()` を使用した直接 DOM 統合 | +| [React](./react) | `@tsparticles/react` | フックとコンポーネント API を備えた公式 React ラッパー | +| [Vue 3](./vue3) | `@tsparticles/vue3` | コンポーザブルを備えた公式 Vue 3 プラグイン | +| [Angular](./angular) | `@tsparticles/angular` | 公式 Angular コンポーネントとモジュール | +| [Svelte](./svelte) | `@tsparticles/svelte` | 公式 Svelte コンポーネント | +| [Next.js](./nextjs) | `@tsparticles/react`(Next.js 使用) | サーバーサイドレンダリングと動的インポート | +| [Nuxt](./nuxt) | `@tsparticles/vue3`(Nuxt 使用) | Nuxt プラグインとしての SSR セーフな統合 | +| [Solid](./solid) | `@tsparticles/solid` | 公式 SolidJS ラッパー | +| [Preact](./preact) | `@tsparticles/preact` | Preact 互換コンポーネント | +| [Lit](./lit) | `@tsparticles/lit` | Lit Web コンポーネントラッパー | +| [Qwik](./qwik) | `@tsparticles/qwik` | Qwik 最適化統合 | +| [jQuery](./jquery) | `@tsparticles/jquery` | レガシープロジェクト向け jQuery プラグイン | +| [Astro](./astro) | `@tsparticles/react`(または任意のラッパー) | クライアントディレクティブを使用したアイランドアーキテクチャ | +| [Web Components](./webcomponents) | `@tsparticles/webcomponents` | Custom Elements API 統合 | +| [Stencil](./stencil) | `@tsparticles/stencil` | Stencil コンポーネントラッパー | +| [Ember](./ember) | `@tsparticles/ember` | Ember アドオン統合 | +| [Riot](./riot) | `@tsparticles/riot` | Riot.js ラッパー | +| [Inferno](./inferno) | `@tsparticles/inferno` | Inferno 互換コンポーネント | +| [WordPress](./wordpress) | プラグイン + `tsparticles` | ブロックエディター / ショートコード統合 | + +## ガイドを選ぶ + +- [Vanilla JS(プレーン JavaScript)](./vanilla) +- [React](./react) +- [Vue 3](./vue3) +- [Angular](./angular) +- [Svelte](./svelte) +- [Next.js](./nextjs) +- [Nuxt](./nuxt) +- [Solid](./solid) +- [Preact](./preact) +- [Lit](./lit) +- [Qwik](./qwik) +- [jQuery](./jquery) +- [Astro](./astro) +- [Web Components](./webcomponents) +- [Stencil](./stencil) +- [Ember](./ember) +- [Riot](./riot) +- [Inferno](./inferno) +- [WordPress](./wordpress) + +Happy building! diff --git a/websites/website/docs/ja/guides/inferno.md b/websites/website/docs/ja/guides/inferno.md new file mode 100644 index 00000000000..c77ec862d56 --- /dev/null +++ b/websites/website/docs/ja/guides/inferno.md @@ -0,0 +1,373 @@ +--- +title: Inferno ガイド +description: tsParticles を Inferno アプリケーションに統合するための完全ガイド。 +--- + +# Inferno ガイド + +## 目次 + +1. [インストール](#installation) +2. [基本的な使い方](#basic-usage) +3. [エンジンの初期化](#engine-initialization) +4. [カスタム設定](#custom-configuration) +5. [プリセットの使用](#preset-usage) +6. [コンポーネントパターン](#component-pattern) +7. [TypeScript の例](#typescript-example) + +--- + +## インストール + +npm を使用して Inferno ラッパーと tsParticles エンジンをインストールします: + +```bash +npm install @tsparticles/inferno tsparticles +``` + +オプションで、より小さなバンドルのためにスリムプリセットをインストールします: + +```bash +npm install @tsparticles/slim +``` + +--- + +## 基本的な使い方 + +`@tsparticles/inferno` パッケージは、`ParticlesProvider` と `Particles` の2つのアイテムをエクスポートします。パーティクルコンポーネントを `ParticlesProvider` でラップします。これはエンジン設定用の `init` コールバックを受け入れ、その後 `` を使用してパーティクルキャンバスをレンダリングします。 + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import { loadSlim } from "@tsparticles/slim"; + +const options = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +function App() { + return ( + { + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +`ParticlesProvider` はすべての `` コンポーネントの祖先である必要があります。エンジンを1回初期化し、コンテキストを介してすべての子に提供します。 + +--- + +## エンジンの初期化 + +`ParticlesProvider` は、エンジンインスタンスを受け取る `init` プロップを受け入れます。ここで、アプリが必要とする機能、シェイプ、プリセット、またはアップデーターをロードします。 + +```tsx +// 軽量 — 円形パーティクル、基本的な移動、リンク + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); +}}> + +// 完全な機能セット — すべてのシェイプ、インタラクション、エフェクト + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); +}}> + +// プリセット固有 — クラッカー、花火、雪、星 + { + const { loadConfettiPreset } = await import("@tsparticles/preset-confetti"); + await loadConfettiPreset(engine); +}}> +``` + +コールバック内で動的な `import()` を使用すると、コード分割が可能になります。プリセットまたは機能モジュールは、パーティクルコンポーネントがマウントされたときにのみロードされます。 + +--- + +## カスタム設定 + +以下は、インタラクティビティ、複数のシェイプタイプ、およびダークグラデーション背景を備えた完全な機能を備えた設定です。 + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, +}; + +function App() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +--- + +## プリセットの使用 + +`@tsparticles/configs` パッケージは、`options` プロップにそのまま渡すことができる構築済みの設定を提供します。`ParticlesProvider` の init コールバックで対応するプリセットローダーと組み合わせます。 + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import configs from "@tsparticles/configs"; + +function App() { + return ( + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +`configs.confetti` は利用可能な任意のプリセットと交換可能です: `configs.basic`、`configs.fireworks`、`configs.snow`、`configs.stars` など。 + +--- + +## コンポーネントパターン + +大規模なアプリケーションでは、パーティクルロジックを専用のコンポーネントに構造化し、`Container` インスタンスにアクセスするための `particlesLoaded` コールバックを備えます。 + +```tsx +import { render, Component } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +class ParticlesBackground extends Component { + private container?: Container; + + handleParticlesLoaded(container?: Container) { + this.container = container; + console.log("Particles loaded:", container?.id); + } + + render() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); + } +} + +function App() { + return ( +
+

tsParticles + Inferno

+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +## TypeScript の例 + +以下は、レスポンシブなパーティクル設定とフルスクリーン背景を備えた、完全な型付けされた Inferno アプリケーションです。 + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const particlesOptions: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +function handleInit(engine: Engine): Promise { + return import("@tsparticles/slim").then(({ loadSlim }) => loadSlim(engine)); +} + +function handleParticlesLoaded(container?: Container): void { + console.log("tsParticles container ready:", container?.id); +} + +function App() { + return ( + +
+

tsParticles + Inferno

+

Full TypeScript integration

+
+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +これで、tsParticles を Inferno アプリケーションに統合するために必要なすべてが揃いました。各例は自己完結型で、プロジェクトにコピーしてすぐに使用できます。 diff --git a/websites/website/docs/ja/guides/jquery.md b/websites/website/docs/ja/guides/jquery.md new file mode 100644 index 00000000000..8017384c732 --- /dev/null +++ b/websites/website/docs/ja/guides/jquery.md @@ -0,0 +1,274 @@ +# jQuery インテグレーション + +公式の jQuery プラグラインラッパーを使用して、tsParticles を jQuery ベースのプロジェクトに統合します。 + +## インストール + +### CDN 経由 + +スクリプトタグを使用して、jQuery、tsParticles、および jQuery プラグインをインクルードします: + +```html + + + +``` + +--- + +### npm + ビルド経由 + +必要なパッケージをインストールします: + +```bash +npm install jquery @tsparticles/jquery tsparticles +``` + +プロジェクトにインポートします: + +```javascript +import $ from "jquery"; +import "@tsparticles/jquery"; +``` + +## エンジンの初期化 + +パーティクルをレンダリングする前に、tsParticles エンジンに必要な機能を初期化する必要があります。これは `$.particles.init` を介して行われます: + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); +})(); +``` + +> **なぜこれが必要なのですか?** tsParticles はモジュラーアーキテクチャを採用しています。`loadFull` はすべての組み込みシェイプ、インタラクション、アップデーターを登録します。より小さなバンドル(例: `tsparticles-slim`)をインポートして、バンドルサイズを削減できます。 + +## 基本的な使い方 + +エンジンが初期化され、DOM の準備ができたら、コンテナ要素を選択して `.particles().load()` を呼び出します: + +```javascript +$(document).ready(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); + + $("#tsparticles") + .particles() + .load({ + background: { + color: "#0d47a1", + }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + }, + }); +}); +``` + +コンテナ要素は DOM に存在する必要があります: + +```html +
+``` + +## カスタム設定 + +`.load()` メソッドは完全な `ISourceOptions` オブジェクトを受け入れます。以下は包括的な例です: + +```javascript +$("#tsparticles") + .particles() + .load({ + background: { + color: "#000000", + }, + fpsLimit: 120, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + direction: "none", + enable: true, + outModes: "bounce", + speed: 4, + }, + number: { + density: { + enable: true, + }, + value: 60, + }, + opacity: { + value: 0.6, + }, + shape: { + type: ["circle", "square", "triangle"], + }, + size: { + value: { min: 2, max: 8 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + }, + interactivity: { + events: { + onClick: { + enable: true, + mode: "push", + }, + onHover: { + enable: true, + mode: "repulse", + }, + }, + modes: { + push: { + quantity: 4, + }, + repulse: { + distance: 200, + }, + }, + }, + }); +``` + +## プリセットのロード + +プリセットパッケージ(例: `tsparticles-preset-stars`)をインストールした場合、エンジン初期化時にロードして設定内で参照します: + +```bash +npm install tsparticles-preset-stars +``` + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadStarsPreset } = await import("tsparticles-preset-stars"); + await loadStarsPreset(engine); + }); + + $("#tsparticles") + .particles() + .load({ + preset: "stars", + background: { color: "#0d47a1" }, + }); +})(); +``` + +## イベント処理とコンテナ制御 + +`.particles()` は jQuery プラグインインスタンスを返します。基礎となる tsParticles の `Container` にアクセスして `play()`、`pause()`、`destroy()` などのメソッドを呼び出すには: + +```javascript +const $container = $("#tsparticles"); + +// パーティクルをロード +$container.particles().load({ + /* options */ +}); + +// 数秒後に再生/一時停止 +setTimeout(() => { + const container = $container.particles().getContainer(); + container?.pause(); +}, 5000); +``` + +## 完全な例 + +以下は、CDN 経由で tsParticles をロードし、インタラクティブエフェクト付きのパーティクルシーンをレンダリングする、完全な自己完結型 HTML ページです: + +```html + + + + + + tsParticles + jQuery + + + +
+ + + + + + + +``` + +## API リファレンス + +| メソッド | 説明 | +| ---------------------------------- | ------------------------------------------------------ | +| `$.particles.init(fn)` | ローダーコールバックでエンジンを初期化します | +| `$(el).particles()` | 要素上にパーティクルプラグインインスタンスを作成します | +| `$(el).particles().load(opts)` | パーティクル設定をロードして開始します | +| `$(el).particles().destroy()` | パーティクルインスタンスを破棄してクリーンアップします | +| `$(el).particles().getContainer()` | 命令的な制御のための基礎となる `Container` を返します | diff --git a/websites/website/docs/ja/guides/lit.md b/websites/website/docs/ja/guides/lit.md new file mode 100644 index 00000000000..1078b3db31c --- /dev/null +++ b/websites/website/docs/ja/guides/lit.md @@ -0,0 +1,301 @@ +--- +title: Lit +description: 公式の @tsparticles/lit Web コンポーネントラッパーを使用して、Lit と tsParticles を統合します。 +--- + +# Lit インテグレーション + +`@tsparticles/lit` パッケージは、Lit で構築された `` カスタム要素を提供し、任意の Lit プロジェクトまたはプレーン HTML ページで tsParticles を宣言的に使用できるようにします。 + +## インストール + +```bash +npm install @tsparticles/lit tsparticles +``` + +このパッケージは完全に型付けされており、パーティクルオプションをリアクティブに更新するための Lit のリアクティブコントローラーパターンが含まれています。 + +## エンジンの初期化 + +`` コンポーネントを登録またはアプリケーションにインポートする前に、`initParticlesEngine` を呼び出します。これは正確に1回実行する必要があります。 + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadFull } from "tsparticles"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +最適化されたバンドルサイズのために、プロジェクトに必要な機能のみをインポートします: + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadBasic } from "@tsparticles/basic"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +void initParticlesEngine(async (engine) => { + await loadBasic(engine); + await loadConfettiPreset(engine); +}); +``` + +## 基本的な使い方 + +エンジンが初期化された後、任意の Lit テンプレートまたは HTML ファイルで `` 要素を使用します: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private options = { + background: { + color: "#0d1117", + }, + particles: { + number: { value: 60 }, + color: { value: "#58a6ff" }, + links: { + enable: true, + color: "#58a6ff", + }, + move: { enable: true, speed: 2 }, + }, + }; + + render() { + return html` `; + } +} +``` + +`.options` 構文(先頭のドット付き)は Lit のプロパティバインディングで、オブジェクトが属性としてシリアライズされるのではなく、参照によって渡されることを保証します。 + +## プレーン HTML での使用 + +`@tsparticles/lit` がバンドルまたはロードされると、この要素はプレーン HTML でも動作します: + +```html + + + + + + + + + +``` + +JSON 属性として最小限の options オブジェクトを渡すこともできます: + +```html + +``` + +## カスタム設定 + +完全な tsParticles 設定を Lit プロパティとして渡します: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-particles") +class MyParticles extends LitElement { + @property({ type: Object }) + options: ISourceOptions = { + background: { + color: "#0d1117", + }, + fpsLimit: 120, + fullScreen: { + enable: true, + zIndex: -1, + }, + particles: { + color: { + value: ["#ff5733", "#33ff57", "#3357ff"], + }, + links: { + color: "#ffffff", + enable: true, + opacity: 0.3, + distance: 150, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + }, + number: { + value: 100, + density: { + enable: true, + }, + }, + opacity: { + value: 0.6, + animation: { + enable: true, + speed: 0.5, + minimumValue: 0.1, + }, + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 2, + minimumValue: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + }, + modes: { + grab: { + distance: 180, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + }; + + render() { + return html` `; + } +} +``` + +## イベント処理 + +`` 要素によってディスパッチされる `particles-loaded` カスタムイベントをリッスンします: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import type { Container } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private handleParticlesLoaded(e: CustomEvent) { + const container = e.detail; + console.log("Particles loaded:", container); + container?.refresh(); + } + + render() { + return html` `; + } +} +``` + +## TypeScript の例 + +`initParticlesEngine`、リアクティブオプション、およびイベント処理を備えた完全に型付けされた Lit 要素: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import { initParticlesEngine } from "@tsparticles/lit"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import "@tsparticles/lit"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +@customElement("particles-background") +class ParticlesBackground extends LitElement { + @property({ type: Object }) + options: ISourceOptions = {}; + + @property({ type: Boolean, attribute: "fullscreen" }) + fullscreen = true; + + protected onParticlesLoaded(e: CustomEvent) { + console.log("Container ready:", e.detail.id); + } + + render() { + return html` + + + `; + } +} +``` + +## 動的更新 + +`` は Lit のリアクティブプロパティを使用するため、`options` プロパティを変更するとパーティクルが自動的に更新されます: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("dynamic-particles") +class DynamicParticles extends LitElement { + @state() + private theme: "light" | "dark" = "dark"; + + private get options(): ISourceOptions { + return this.theme === "dark" + ? { + background: { color: "#0d1117" }, + particles: { color: { value: "#58a6ff" } }, + } + : { + background: { color: "#ffffff" }, + particles: { color: { value: "#0969da" } }, + }; + } + + private toggleTheme() { + this.theme = this.theme === "dark" ? "light" : "dark"; + } + + render() { + return html` + + + `; + } +} +``` + +コンポーネントは `options` プロパティを監視し、変更されるたびに内部的に `refresh()` を呼び出し、実行時にシームレスにパーティクル設定を更新します。 diff --git a/websites/website/docs/ja/guides/nextjs.md b/websites/website/docs/ja/guides/nextjs.md new file mode 100644 index 00000000000..18f12c4d476 --- /dev/null +++ b/websites/website/docs/ja/guides/nextjs.md @@ -0,0 +1,492 @@ +--- +title: Next.js インテグレーション +description: App Router を使用して tsParticles を Next.js アプリケーションに統合するためのステップバイステップガイド。 +--- + +# Next.js インテグレーション + +このガイドでは、**App Router**(Next.js 13+)を使用して tsParticles を Next.js プロジェクトに統合する方法を説明します。従来の Pages Router については、下部の [従来の Pages Router](#legacy-pages-router) セクションを参照してください。 + +## インストール + +`@tsparticles/react` ラッパーと完全な `tsparticles` エンジン(またはより小さなビルド用のスリムバンドル)をインストールします: + +```bash +npm install @tsparticles/react tsparticles +``` + +より小さな `@tsparticles/slim` バンドルを希望する場合: + +```bash +npm install @tsparticles/react @tsparticles/slim +``` + +## 基本的な使い方(App Router) + +Next.js App Router のコンポーネントはデフォルトでサーバーサイドです。tsParticles はブラウザの `canvas` API を必要とするため、コンポーネントに `"use client"` ディレクティブを指定する必要があります。 + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesBackground() { + const particlesLoaded = useCallback((container?: Container) => { + console.log("Particles loaded", container); + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }), + [], + ); + + return ; +} +``` + +これを `components/particles-background.tsx` として作成し、任意のページまたはレイアウトにインポートします。ファイルが `"use client"` で始まるため、クライアントでレンダリングされます — tsParticles が必要とするまさにその場所です。 + +## テーマ切り替え + +tsParticles を Next.js のテーマトグルと組み合わせて、現在のテーマ状態からオプションを導出します: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useMemo, useState, useCallback } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ThemeAwareParticles() { + const [theme, setTheme] = useState<"light" | "dark">("dark"); + + const toggleTheme = useCallback(() => { + setTheme((t) => (t === "dark" ? "light" : "dark")); + }, []); + + const particlesLoaded = useCallback((_container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { + color: theme === "dark" ? "#000000" : "#ffffff", + }, + particles: { + color: { value: theme === "dark" ? "#ffffff" : "#000000" }, + number: { value: 100 }, + links: { + enable: true, + color: theme === "dark" ? "#ffffff" : "#000000", + }, + move: { enable: true }, + }, + }), + [theme], + ); + + return ( + <> + + + + ); +} +``` + +`options` オブジェクトは `theme` が変更されるたびに `useMemo` を介して再作成されるため、キャンバスは自動的に更新されます。 + +## クラッカーエフェクト + +`@tsparticles/preset-confetti` を使用して、ボタンクリックなどのイベントでお祝いのクラッカーを発生させます: + +```bash +npm install @tsparticles/preset-confetti +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Container, ISourceOptions, Engine } from "@tsparticles/engine"; + +export default function ConfettiButton() { + const [active, setActive] = useState(false); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadConfettiPreset(engine); + }, []); + + const particlesLoaded = useCallback( + async (container?: Container) => { + if (active && container) { + await container.play(); + } + }, + [active], + ); + + const options: ISourceOptions = useMemo( + () => ({ + preset: "confetti", + fullScreen: { zIndex: 1000 }, + }), + [], + ); + + const handleCelebrate = useCallback(() => { + setActive(true); + setTimeout(() => setActive(false), 5000); + }, []); + + return ( + <> + {active && } + + + ); +} +``` + +`init` コールバックは、パーティクルが作成される前にクラッカープリセットをエンジンにロードします。 + +## 花火エフェクト + +同様に、花火プリセットは壮観な花火ディスプレイを作成します: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; +import type { Container, Engine } from "@tsparticles/engine"; + +export default function FireworksBackground() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFireworksPreset(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options = useMemo( + () => ({ + preset: "fireworks" as const, + fullScreen: { zIndex: -1 }, + background: { + color: "#000", + }, + }), + [], + ); + + return ; +} +``` + +## Container 参照を使用した完全な TypeScript の例 + +`Container` インスタンスにアクセスして、アニメーションをプログラムで制御します(再生、一時停止、破棄、画像エクスポート): + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +export default function ControllableParticles() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFull(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + fpsLimit: 120, + interactivity: { + events: { + onClick: { enable: true, mode: "push" }, + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + push: { quantity: 4 }, + repulse: { distance: 100 }, + }, + }, + particles: { + color: { value: "#ff0000" }, + links: { + enable: true, + color: "#ff0000", + distance: 150, + }, + move: { enable: true, speed: 2 }, + number: { value: 60 }, + size: { value: { min: 1, max: 5 } }, + }, + }), + [], + ); + + const handlePause = useCallback(() => { + containerRef.current?.pause(); + }, []); + + const handlePlay = useCallback(() => { + containerRef.current?.play(); + }, []); + + return ( +
+ +
+ + +
+
+ ); +} +``` + +重要なポイント: + +- `particlesInit` はエンジンの機能をロードします(コンポーネントのマウントごとに1回のみ実行されます)。 +- `particlesLoaded` はコンテナが完全に初期化されるたびに発生します。 +- `containerRef` は `Container` インスタンスを保持するため、後でそのメソッドを呼び出すことができます。 + +## パフォーマンス: useMemo と useCallback + +静的またはほとんど変更されないオプションは常に `useMemo` でラップし、イベントハンドラーは `useCallback` でラップして、キャンバスの不要な再レンダリングを防ぎます: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function PerformanceExample() { + const [particlesCount, setParticlesCount] = useState(80); + + // 安定したコールバック — 依存関係が変更されない限り再作成されない + const particlesLoaded = useCallback((container?: Container) => { + console.log("Container ready", container?.id); + }, []); + + // 安定したオプションオブジェクト — キャンバスの再初期化を防ぐ + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: particlesCount }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [particlesCount], + ); + + return ( +
+ + +
+ ); +} +``` + +これらの最適化がないと、親が再レンダリングされるたびに新しい `options` オブジェクトが作成され、キャンバスが再作成されることになります。 + +## ページ統合 + +ページコンテンツに影響を与えずに、ページレイアウトにパーティクル背景を追加します: + +```tsx +// app/layout.tsx(サーバーコンポーネント) +import dynamic from "next/dynamic"; + +const ParticlesBackground = dynamic(() => import("@/components/particles-background"), { ssr: false }); + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + +
{children}
+ + + ); +} +``` + +`ssr: false` を指定した `dynamic()` を使用して、コンポーネントがサーバーサイドレンダリング中に実行されることがないようにします。パーティクルキャンバスは CSS の `z-index` を介してメインコンテンツの背後に配置されます。 + +## 複数のインスタンス + +同じページに複数の独立した `Particles` コンポーネントを、それぞれ独自の設定でレンダリングできます: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +function ParticlesGallery() { + const loaded = useCallback((c?: Container) => {}, []); + + const redOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#1a0000" }, + particles: { + color: { value: "#ff0000" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + const blueOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#00001a" }, + particles: { + color: { value: "#0000ff" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + return ( +
+ + +
+ ); +} +``` + +各 `Particles` コンポーネントは、独自のアニメーションループを持つ独立したキャンバスを作成します。`fullScreen: false` を設定し、それぞれに固定の高さを指定して、ドキュメントフロー内で共存できるようにします。 + +## 従来の Pages Router + +Next.js の **Pages Router**(`pages/` ディレクトリ)を使用している場合、アプローチは似ていますが、`"use client"` ディレクティブは必要ありません。代わりに、ページコンポーネントで動的インポートを使用できます: + +```tsx +// pages/index.tsx +import dynamic from "next/dynamic"; +import type { NextPage } from "next"; + +const ParticlesComponent = dynamic(() => import("../components/particles-component"), { ssr: false }); + +const Home: NextPage = () => { + return ( +
+ +

Welcome

+
+ ); +}; + +export default Home; +``` + +コンポーネント自体(`components/particles-component.tsx`)はプレーンな React コンポーネントです: + +```tsx +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesComponent() { + const particlesLoaded = useCallback((container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 80 }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [], + ); + + return ; +} +``` + +Pages Router は `"use client"` を**必要としない**ことに注意してください。ページコンポーネントはデフォルトでクライアントレンダリングされるためです。 + +## トラブルシューティング + +| 症状 | 原因 | 修正 | +| ------------------------------ | ------------------------------------------------ | ------------------------------------------------------------------------------- | +| 空白の白いページ | SSR が canvas 依存モジュールをレンダリング | `dynamic(..., { ssr: false })` を使用するか、クライアントコンポーネントでラップ | +| キャンバスが表示されない | コンテナの高さがゼロ | `fullScreen: { zIndex: -1 }` を設定するか、明示的な寸法を指定 | +| オプションの変更が反映されない | 新しいオブジェクト参照が作成されていない | 適切な依存配列を持つ `useMemo` を使用 | +| プリセットが動作しない | コンテナ初期化前にプリセットがロードされていない | `init` コールバック内で `loadXPreset(engine)` を呼び出す | + +## 次のステップ + +- [インタラクティブデモ](/demos/) で既成の設定を参照してください。 +- すべての利用可能なパラメーターについては、完全な [オプションリファレンス](/options/) をお読みください。 +- 雪、星、ホタルなどのより多くのプリセットについては、[プリセット](/demos/presets) ページをチェックしてください。 diff --git a/websites/website/docs/ja/guides/nuxt.md b/websites/website/docs/ja/guides/nuxt.md new file mode 100644 index 00000000000..1226e67a7fb --- /dev/null +++ b/websites/website/docs/ja/guides/nuxt.md @@ -0,0 +1,463 @@ +--- +title: Nuxt インテグレーション +description: tsParticles を Nuxt 3 / Nuxt 4 アプリケーションに統合するためのステップバイステップガイド。 +--- + +# Nuxt インテグレーション + +このガイドでは、公式の `@tsparticles/vue3` ラッパーを使用して **Nuxt 3**(および Nuxt 4)プロジェクトに tsParticles を統合する方法を説明します。Nuxt はサーバーサイドとクライアントサイドの両方で実行されるため、SSR からパーティクルコンポーネントを保護する必要があります。 + +## インストール + +Vue 3 ラッパーと選択したエンジンバンドルをインストールします: + +```bash +npm install @tsparticles/vue3 tsparticles +``` + +より小さなバンドルには、`tsparticles` の代わりに `@tsparticles/slim` をインストールします: + +```bash +npm install @tsparticles/vue3 @tsparticles/slim +``` + +## 基本的な使い方 + +Nuxt はデフォルトでコンポーネントをサーバー上でレンダリングします。tsParticles はブラウザの `canvas` API を必要とするため、`` コンポーネントを `` タグでラップする必要があります: + +```vue + + + + + +``` + +`` ラッパーにより、`` コンポーネントがブラウザでのみマウントされ、ハイドレーションの不一致を防ぎます。 + +## 設定 + +タイプセーフな設定には完全な `ISourceOptions` 型を使用します。オプションはインラインで定義するか、別の設定ファイルからインポートできます: + +```vue + +``` + +## 雪エフェクト + +雪プリセットを使用して冬の降雪エフェクトを作成します: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +プリセットが ` +``` + +利用可能なインタラクションモード: `grab`、`bubble`、`connect`、`repulse`、`push`、`remove`、`attract`、`slow`。 + +## イベント処理 + +`` コンポーネントはいくつかのライフサイクルイベントを発行します: + +```vue + + + +``` + +| イベント | ペイロード | 説明 | +| -------------------- | ----------- | -------------------------------------------------- | +| `@particles-init` | `Engine` | tsParticles エンジンが初期化されたときに1回発生 | +| `@particles-loaded` | `Container` | コンテナのロードまたはリロードが完了するたびに発生 | +| `@particles-destroy` | なし | コンテナが破棄されたときに発生 | + +## 完全な TypeScript の例 + +明示的なインポートとライフサイクル認識を備えた、完全な型付けされたコンポーネント: + +```vue + + + + + +``` + +## ページ統合 + +特定の Nuxt ページにパーティクル背景を追加するには、ページのテンプレートにコンポーネントを配置します: + +```vue + + + + + +``` + +**すべての** ページにパーティクルを表示したい場合は、個々のページではなく `layouts/default.vue` にコンポーネントを追加します。 + +## Nuxt 4 の注意点 + +Nuxt 4 は Nuxt 3 の `` および ` +``` + +## トラブルシューティング + +| 症状 | 原因 | 修正 | +| ----------------------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------- | +| 空白画面 / ハイドレーションエラー | `` がサーバー上でレンダリング | `` でラップ | +| プリセットが効果を発揮しない | コンポーネントマウント前にプリセットがロードされていない | ` + +``` + +エンジンは1回初期化され、アプリ内のすべての `` インスタンス間で共有されます。 + +--- + +## 基本的な使い方 + +エンジンを初期化した後、テンプレートで `` コンポーネントを使用します。設定は JSON 文字列化された options オブジェクトまたはコンポーネントのプロパティへの参照として渡します。 + +```html + + + + + +``` + +--- + +## 条件付きレンダリング + +Riot の `if={}` ディレクティブを状態プロパティとともに使用して、エンジンの初期化が完了するまでパーティクルコンポーネントのレンダリングを遅延させます。これにより、レイアウトシフトを回避し、コンポーネントが準備完了のエンジンを受け取ることを保証します。 + +```html + + + + + +``` + +`this.update()` を呼び出すと再レンダリングがトリガーされ、プロミスが解決されると `` タグが表示されます。 + +--- + +## プリセットの使用 + +`@tsparticles/configs` パッケージは、クラッカー、花火、雪、星などの一般的なエフェクト用の構築済み設定を提供します。これらを options オブジェクトとして直接使用します。 + +```html + + + + + +``` + +利用可能なプリセットには、`basic`、`confetti`、`fireworks`、`snow`、`stars` などがあります。各プリセットは、エンジンコールバックに対応するプリセットパッケージをロードする必要があります。たとえば、`configs.fireworks` には `loadFireworksPreset` が必要です。 + +--- + +## カスタム設定 + +インタラクティビティ、複数のシェイプタイプ、高度なアニメーションオプションを備えたカスタム設定を構築します。 + +```html + + + + + +``` + +--- + +## 完全なコンポーネント + +以下は、すべてをまとめた完全な `.riot` ファイルです: `onBeforeMount` でのエンジン初期化、状態による条件付きレンダリング、インタラクティビティを備えたリッチな設定、およびロードされたイベントのサポートを介した `particlesLoaded` コールバック。 + +```html + +
+

tsParticles + Riot.js

+ + {#if state.particlesInitialized} + + {:else} +

Loading particle engine...

+ {/if} +
+ + + + +
+``` + +--- + +これで、tsParticles を Riot.js アプリケーションに統合するために必要なすべてが揃いました。各例は自己完結型で、プロジェクトにコピーしてすぐに使用できます。 diff --git a/websites/website/docs/ja/guides/solid.md b/websites/website/docs/ja/guides/solid.md new file mode 100644 index 00000000000..d155e66d97d --- /dev/null +++ b/websites/website/docs/ja/guides/solid.md @@ -0,0 +1,511 @@ +--- +title: SolidJS インテグレーション +description: 公式の @tsparticles/solid ラッパーを使用して tsParticles を SolidJS アプリケーションに統合するためのステップバイステップガイド。 +--- + +# SolidJS インテグレーション + +このガイドでは、公式の `@tsparticles/solid` ラッパーを使用して **SolidJS** プロジェクトに tsParticles を統合する方法を説明します。SolidJS のきめ細かいリアクティビティモデルは tsParticles と相性が良く、オプションの変更が完全な再初期化なしでターゲットを絞ったキャンバス更新をトリガーします。 + +## インストール + +SolidJS ラッパーと選択したエンジンバンドルをインストールします: + +```bash +npm install @tsparticles/solid tsparticles +``` + +より小さなバンドルには、`@tsparticles/slim` を使用します: + +```bash +npm install @tsparticles/solid @tsparticles/slim +``` + +## 基本的な使い方 + +SolidJS は完全にブラウザで実行されるため(SSR なし)、サーバーレンダリングに対するガードは必要ありません。ただし、パーティクルをレンダリングする前にエンジンを非同期で初期化する必要があります。 + +`onMount` 内で `initParticlesEngine` を使用してエンジン機能をロードし、`` で条件付きで `` コンポーネントをレンダリングします: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [initialized, setInitialized] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setInitialized(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +`` コンポーネントは、エンジンの準備ができた後にのみ `` 要素が DOM に挿入されるようにします。 + +## エンジンの初期化 + +`initParticlesEngine` 関数は、`Engine` インスタンスを受け取るコールバックを受け入れます。このコールバックを使用して、設定に必要な機能を登録します: + +```tsx +import { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import { loadSlim } from "@tsparticles/slim"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Engine } from "@tsparticles/engine"; + +// 最小限 — 基本的なシェイプと移動のみ +initParticlesEngine((engine: Engine) => loadSlim(engine)).then(() => { + console.log("Engine ready (slim)"); +}); + +// 完全 — すべての機能を含む +initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => { + console.log("Engine ready (full)"); +}); + +// プリセットのみ — 特定のプリセットに必要な機能のみ +initParticlesEngine((engine: Engine) => loadConfettiPreset(engine)).then(() => { + console.log("Confetti preset loaded"); +}); +``` + +`initParticlesEngine` はアプリ内で1回呼び出します — 通常はルートコンポーネントの `onMount` で行います。エンジンインスタンスはキャッシュされるため、後続の呼び出しは即座に返ります。 + +## 条件付きレンダリング + +SolidJS の `` 制御フローを使用して、エンジンが初期化されるまでレンダリングを延期します: + +```tsx +import { createSignal, Show, onMount } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import type { Engine } from "@tsparticles/engine"; +import type { Component } from "solid-js"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + Loading particles...

}> + +
+ ); +}; +``` + +`fallback` プロップは、エンジン初期化中にローディングインジケーターを表示します。 + +## プリセットの使用 + +クイックでデザイン済みの設定には `@tsparticles/configs` を使用します: + +```bash +npm install @tsparticles/configs +``` + +```tsx +import configs from "@tsparticles/configs"; +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + +
+ + +
+
+ ); +}; + +export default App; +``` + +利用可能な設定には、`basic`、`bubbles`、`snow`、`stars`、`fireworks`、`confetti`、`links` などがあります。 + +## インタラクティブパーティクル + +`interactivity` セクションを設定して、クリックとホバーのインタラクションを追加します: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 60 }, + links: { enable: true, distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 4 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +- **ホバーモード**: `grab`、`bubble`、`repulse`、`attract`、`slow`、`connect` +- **クリックモード**: `push`、`remove`、`repulse`、`bubble`、`attract`、`pause` + +## カスタム設定 + +複数のパーティクルシェイプ、カラーパレット、モーション設定を備えた完全なカスタム設定: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0a0a23" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { enable: true, rotateX: 600, rotateY: 1200 }, + }, + number: { + value: 40, + density: { enable: true }, + }, + opacity: { + value: { min: 0.3, max: 0.8 }, + animation: { + enable: true, + speed: 0.5, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + animation: { + enable: true, + speed: 2, + sync: false, + }, + }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.3, + width: 1, + }, + shape: { + type: ["circle", "square", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + twinkle: { + particles: { + enable: true, + frequency: 0.05, + opacity: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "bubble" }, + }, + modes: { + repulse: { distance: 120 }, + bubble: { distance: 200, size: 10, opacity: 0.8 }, + }, + }, + detectRetina: true, + }; + + return ( + + + + ); +}; + +export default App; +``` + +## 完全な TypeScript の例 + +コンテナ参照、エンジン初期化、手動コントロールを備えた完全な型付けコンポーネント: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [container, setContainer] = createSignal(undefined); + const [paused, setPaused] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#1a1a2e" }, + particles: { + color: { value: "#e94560" }, + number: { value: 80 }, + links: { enable: true, color: "#e94560", distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 5 } }, + }, + }; + + const particlesLoaded = (c: Container) => { + setContainer(c); + }; + + const togglePause = () => { + const c = container(); + if (c) { + if (paused()) { + c.play(); + } else { + c.pause(); + } + setPaused(!paused()); + } + }; + + return ( + + + + + ); +}; + +export default App; +``` + +## シグナルを使用した動的オプション + +SolidJS の強みの1つはきめ細かいリアクティビティです。シグナルを使用してパーティクルオプションを駆動すると、キャンバスが効率的に更新されます: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [color, setColor] = createSignal("#ff0000"); + const [particleCount, setParticleCount] = createSignal(60); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + // options は通常のオブジェクトです — Particle コンポーネントの内部追跡を通じてリアクティブに読み取られます + const options = (): ISourceOptions => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#000" }, + particles: { + color: { value: color() }, + number: { value: particleCount() }, + links: { enable: true, color: color() }, + move: { enable: true }, + }, + }); + + return ( + + {}} /> +
+ + +
+
+ ); +}; + +export default App; +``` + +`options` はシグナルにアクセスする関数であるため、`color()` または `particleCount()` が変更されるたびに、`` コンポーネントは新しい options オブジェクトを受け取り、変更されたプロパティのみを既存のキャンバスに適用します。 + +## カスタムオーバーライド付きプリセット + +プリセットをロードし、カスタムオーバーライドをマージして調整されたエフェクトを作成します: + +```tsx +import { loadSnowPreset } from "@tsparticles/preset-snow"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadSnowPreset(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + preset: "snow", + fullScreen: { zIndex: -1 }, + background: { color: "#0d0d2b" }, + particles: { + // 雪の色を青にオーバーライド + color: { value: "#88ccff" }, + // フレークの数を増やす + number: { value: 300 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +プリセットはすべてのオプションにデフォルト値を提供し、オーバーライドはその上にマージされます — 変更したいプロパティのみを指定する必要があります。 + +## トラブルシューティング + +| 症状 | 原因 | 修正 | +| ------------------------------ | ----------------------------------------------- | ---------------------------------------------------------------------------------------- | +| 空の DOM 要素 | レンダリング前にエンジンが初期化されていない | `` を `` でラップ | +| パーティクルが表示されない | `move.enable` または `number.value` がない | `particles.move.enable: true` と `particles.number.value > 0` を確認 | +| キャンバスがコンテンツの背後 | fullScreen に `zIndex` がない | `fullScreen: { zIndex: -1 }` を使用 | +| オプションの変更が反映されない | オブジェクト参照が変更されていない | オプションを関数またはストアでラップ; 静的オブジェクトを避ける | +| エンジンが見つからない | `loadFull` または `loadSlim` のインポートがない | `tsparticles` または `@tsparticles/slim` をインストールし、`loadFull(engine)` を呼び出す | + +## 次のステップ + +- [Configs プレイグラウンド](/playground/configs) ですぐに使える設定を探索してください。 +- パラメーターの完全なリストについては、[オプションリファレンス](/options/) をお読みください。 +- GitHub の [SolidJS ソース](https://github.com/tsparticles/solid) でラッパーの内部を確認してください。 diff --git a/websites/website/docs/ja/guides/stencil.md b/websites/website/docs/ja/guides/stencil.md new file mode 100644 index 00000000000..4368626bc4c --- /dev/null +++ b/websites/website/docs/ja/guides/stencil.md @@ -0,0 +1,359 @@ +--- +title: Stencil ガイド +description: tsParticles を Stencil コンポーネントと統合するための完全ガイド。 +--- + +# Stencil ガイド + +## 目次 + +1. [インストール](#installation) +2. [カスタム要素の登録](#custom-elements-registration) +3. [基本的な使い方](#basic-usage) +4. [エンジンの初期化](#engine-initialization) +5. [カスタム設定](#custom-configuration) +6. [コンポーネントライフサイクル](#component-lifecycle) +7. [TypeScript の例](#typescript-example) + +--- + +## インストール + +npm を使用して Stencil ラッパーと tsParticles エンジンをインストールします: + +```bash +npm install @tsparticles/stencil tsparticles +``` + +オプションで、手動設定を減らすためのプリセットバンドルをインストールします: + +```bash +npm install @tsparticles/slim +``` + +--- + +## カスタム要素の登録 + +`@tsparticles/stencil` パッケージは、`` カスタム要素をブラウザに登録する `defineCustomElements` 関数を提供します。アプリ内のどこかでコンポーネントを使用する前に、1回呼び出します。 + +```tsx +import { defineCustomElements } from "@tsparticles/stencil/loader"; + +// 要素を登録 +defineCustomElements(); +``` + +Stencil プロジェクトで遅延読み込みを使用する場合、レンダリング前に要素が利用可能になるように、`componentWillLoad` 内またはアプリのルートコンポーネントでこれを呼び出します。 + +--- + +## 基本的な使い方 + +カスタム要素が登録されたら、JSX で `options` プロップと、必要なエンジン機能をロードするための `init` コールバックを指定して `` を使用できます。 + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +@Component({ tag: "my-particles" }) +export class MyParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## エンジンの初期化 + +`init` プロップはエンジンインスタンスを受け取り、必要な機能をロードできます。ここで `loadSlim`、`loadFull`、または個々のアップデーター/インタラクションプラグインを呼び出すことをお勧めします。 + +```tsx +import { loadSlim } from "@tsparticles/slim"; +import { loadFull } from "tsparticles"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// オプション A: 軽量(円、基本移動、リンク) +init={async engine => { await loadSlim(engine); }} + +// オプション B: 完全な機能セット(すべてのシェイプ、エフェクト、プリセット) +init={async engine => { await loadFull(engine); }} + +// オプション C: プリセット(クラッカー、花火、雪、星) +init={async engine => { await loadConfettiPreset(engine); }} +``` + +エンジンインスタンスは、初期化後にも `container-id` 属性を通じてアクセス可能で、必要に応じて後でパーティクルシステムをプログラムで制御できます。 + +--- + +## カスタム設定 + +以下は、インタラクティビティ、複数のシェイプタイプ、ホバー/クリックモードを備えた完全な設定です。 + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const fullOptions: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { + color: "#0f0f23", + }, +}; + +@Component({ tag: "app-particles" }) +export class AppParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## コンポーネントライフサイクル + +Stencil では、1回限りのセットアップに推奨されるライフサイクルフックは `componentWillLoad` です。これを使用してカスタム要素を登録し、初期化状態を管理して、`` コンポーネントがエンジンの準備ができたときにのみレンダリングされるようにします。 + +```tsx +import { Component, h, State } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ tag: "app-root" }) +export class AppRoot { + @State() private engineReady = false; + + private options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { + enable: true, + speed: 1, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#1a1a2e" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.engineReady = true; + } + + render() { + return ( +
+

tsParticles + Stencil

+ {this.engineReady && ( + { + await loadSlim(engine); + }} + /> + )} +
+ ); + } +} +``` + +`@State()` を使用すると、エンジンの準備ができたときにコンポーネントが再レンダリングされ、条件付きレンダリングにより、カスタム要素が定義される前にパーティクルコンテナがマウントされるのを防ぎます。 + +--- + +## TypeScript の例 + +以下は、スリムプリセット、ホバーインタラクティビティ、カスタムダークテーマを統合した、完全な型付けの Stencil アプリケーションコンポーネントです。 + +```tsx +import { Component, h, State, Prop } from "@stencil/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ + tag: "app-home", + styleUrl: "app-home.css", + shadow: true, +}) +export class AppHome { + @State() private initialized = false; + + @Prop() readonly title: string = "Welcome"; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.initialized = true; + } + + private handleInit = async (engine: Engine): Promise => { + await loadSlim(engine); + }; + + private handleLoaded = async (container?: Container): Promise => { + this.container = container; + console.log("Particles container loaded:", container?.id); + }; + + render() { + return ( +
+

{this.title}

+

Powered by tsParticles and Stencil

+ + {this.initialized && ( + + )} +
+ ); + } +} +``` + +`particlesLoaded` イベントは最初のフレームがレンダリングされた後に発生し、プログラム制御(再生、一時停止、停止、テーマの切り替え)のために `Container` インスタンスへのアクセスを提供します。 + +--- + +これで、tsParticles を Stencil アプリケーションに統合するために必要なすべてが揃いました。各例は自己完結型で、プロジェクトにコピーしてすぐに使用できます。 diff --git a/websites/website/docs/ja/guides/svelte.md b/websites/website/docs/ja/guides/svelte.md new file mode 100644 index 00000000000..2b86da3613a --- /dev/null +++ b/websites/website/docs/ja/guides/svelte.md @@ -0,0 +1,580 @@ +--- +title: Svelte インテグレーション +description: "@tsparticles/svelte を使用して tsParticles を Svelte および SvelteKit アプリケーションに統合するためのステップバイステップガイド。" +--- + +# Svelte インテグレーション + +`@tsparticles/svelte` パッケージは、tsParticles のネイティブ Svelte コンポーネントを提供します。このガイドでは、Svelte(Vite 使用)と SvelteKit について、リアクティブオプション、イベント処理、複数インスタンスを含めて説明します。 + +--- + +## インストール + +```bash +npm install @tsparticles/svelte @tsparticles/engine +``` + +完全なバンドルまたはプリセットの場合: + +```bash +npm install tsparticles +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +``` + +--- + +## 基本的な使い方 + +```svelte + + + +``` + +--- + +## エンジンの初期化 + +アプリに必要なプラグインとプリセットをロードするために、`on:init` イベントハンドラーを渡します: + +```svelte + + + +``` + +または、マウント前に `initParticlesEngine` ユーティリティを使用します: + +```svelte + + +{#if ready} + +{/if} +``` + +--- + +## 雪エフェクト + +```bash +npm install @tsparticles/preset-snow +``` + +```svelte + + + +``` + +追加オプションをマージしてプリセットの動作をカスタマイズします: + +```svelte + +``` + +--- + +## 星エフェクト + +```bash +npm install @tsparticles/preset-stars +``` + +```svelte + + + +``` + +--- + +## インタラクティブパーティクル + +マウスホバーとクリックのインタラクティビティを追加します: + +```svelte + + + +``` + +--- + +## イベント処理 + +```svelte + + +
+ + + +
+ + +``` + +| イベント | 詳細 | 発生タイミング | +| -------------------- | ----------- | ---------------------------- | +| `on:init` | `Engine` | エンジンが初期化された後 | +| `on:particlesLoaded` | `Container` | コンテナが完全に準備できた後 | + +--- + +## TypeScript の例 + +完全な型付けコンポーネント: + +```svelte + + + +``` + +--- + +## 動的オプション + +リアクティブオプションは、インスタンスを再作成せずにパーティクルを更新します: + +```svelte + + +
+ +
+ + +``` + +`$:` リアクティブ宣言は、`color` が変更されるたびに `options` を再計算し、`Particles` コンポーネントが新しい設定を自動的に取得します。 + +--- + +## 複数のインスタンス + +同じページに複数の独立したパーティクルシステムをレンダリングします: + +```svelte + + +
+
+ +
+
+ +
+
+``` + +各 `` コンポーネントは、独自の `id`、キャンバス、およびエンジンコンテキストを取得します。 + +--- + +## SvelteKit での使用 + +SvelteKit では、キャンバスはブラウザ環境を必要とします。コンポーネントの SSR を無効にします: + +```svelte + + +{#if Component} + +{/if} +``` + +または、インポートをクライアント専用コンポーネントでラップします。SvelteKit 2+ では、`vite-plugin-svelte` SSR 除外を使用することもできます。 + +--- + +## API リファレンス + +| プロップ | タイプ | デフォルト | 説明 | +| --------- | ---------------- | --------------- | ---------------------------- | +| `id` | `string` | `"tsparticles"` | キャンバス要素 ID | +| `options` | `ISourceOptions` | `{}` | パーティクル設定オブジェクト | +| `url` | `string` | — | リモート JSON 設定の URL | + +| イベント | 詳細 | 説明 | +| -------------------- | ----------- | -------------------------------------------------------------------- | +| `on:init` | `Engine` | エンジンが初期化されたときに発生(プラグインをロードするために使用) | +| `on:particlesLoaded` | `Container` | コンテナが完全に準備できたときに発生 | + +--- + +## トラブルシューティング + +- **キャンバスが表示されない** — 親コンテナに明示的な寸法(`height: 100%`、`height: 100vh`、または固定ピクセル値)があることを確認してください。 +- **`loadFull is not a function`** — `tsparticles` がインストールされていて、`loadFull` を `tsparticles`(`@tsparticles/engine` ではない)からインポートしていることを確認してください。 +- **リアクティビティが機能しない** — `options` がリアクティブ変数(`$:` またはリアクティブソースにバインドされた `let`)であることを確認してください。プレーンな `const` 値は更新されません。 +- **SvelteKit の空白画面** — `@tsparticles/svelte` を動的にインポートするか、上記の SvelteKit セクションに示すように `browser` ガードを使用してください。 +- **`event.detail` の TypeScript エラー** — イベントハンドラーに `CustomEvent` および `CustomEvent` 型を使用してください。 diff --git a/websites/website/docs/ja/guides/vanilla.md b/websites/website/docs/ja/guides/vanilla.md new file mode 100644 index 00000000000..ad56c2dfb50 --- /dev/null +++ b/websites/website/docs/ja/guides/vanilla.md @@ -0,0 +1,889 @@ +--- +title: Vanilla JS ガイド +description: tsParticles をプレーンな JavaScript と統合するための完全ガイド。 +--- + +# Vanilla JS ガイド + +## 目次 + +1. [はじめに](#getting-started) +2. [基本のパーティクル](#basic-particles) +3. [紙吹雪エフェクト](#confetti-effect) +4. [花火エフェクト](#fireworks-effect) +5. [リボンエフェクト](#ribbons-effect) +6. [雪エフェクト](#snow-effect) +7. [ネットワーク / リンクエフェクト](#network-links-effect) +8. [星エフェクト](#stars-effect) +9. [カスタム設定](#custom-configuration) +10. [複数コンテナ](#multiple-containers) +11. [動的コントロール](#dynamic-controls) + +--- + +## はじめに + +### CDN(クイックスタート) + +HTML に `
` プレースホルダーと script タグを追加します。最低でもエンジンとバンドルが必要で、`tsParticles.load()` の前にローダーを呼び出す必要があります。 + +```html + + + + + + tsParticles – はじめに + + + +
+ + + + + + +``` + +### npm + +```bash +npm install @tsparticles/engine @tsparticles/slim +``` + +次にインポートして使用します: + +```javascript +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +(async () => { + await loadSlim(tsParticles); + + await tsParticles.load({ + id: "tsparticles", + options: { + /* ... */ + }, + }); +})(); +``` + +> **注意:** `@tsparticles/engine` だけでは何も描画されません。バンドル(`@tsparticles/slim` 推奨)または個別のプラグインをインストールして、表示可能なシェイプを取得する必要があります。 + +--- + +## 基本のパーティクル + +円形のシェイプ、ランダムな色、穏やかな動きで 100 個のパーティクルを描画する最小限の設定です。v4 では、パーティクルの色は以前の `color` プロパティではなく `paint` を使用して設定します。 + +```html + + + + + + 基本のパーティクル + + + +
+ + + + + + +``` + +--- + +## 紙吹雪エフェクト + +専用の `@tsparticles/confetti` バンドルを使用して、単一の関数呼び出しでお祝いの紙吹雪を表示します。 + +```html + + + + + + 紙吹雪 + + + + + + + + + +``` + +--- + +## 花火エフェクト + +専用の `@tsparticles/fireworks` バンドルを使用した、効果音付きの花火ショーです。 + +```html + + + + + + 花火 + + + + + + + +``` + +--- + +## リボンエフェクト + +専用の `@tsparticles/ribbons` バンドルを使用して、マウスの位置に反応する流れるようなリボンアニメーションを表示します。 + +```html + + + + + + リボン + + + + + + + +``` + +--- + +## 雪エフェクト + +`@tsparticles/configs` プリセットカタログを使用した、優しく降り注ぐ雪の結晶です。 + +```html + + + + + + 雪エフェクト + + + +
+ + + + + + + +``` + +または、スタンドアロンのプリセットパッケージを使用する方法: + +```html + + + + +``` + +--- + +## ネットワーク / リンクエフェクト + +マウスインタラクション付きの、古典的な連結ノードのビジュアルです。`@tsparticles/slim` バンドルにはリンクインタラクションとマウスグラブモードが含まれています。 + +```html + + + + + + ネットワーク / リンク + + + +
+ + + + + + +``` + +--- + +## 星エフェクト + +`@tsparticles/configs` プリセットカタログを使用した星空の夜空です。 + +```html + + + + + + 星エフェクト + + + +
+ + + + + + + +``` + +または、スタンドアロンのプリセットパッケージを使用する方法: + +```html + + + + +``` + +--- + +## カスタム設定 + +slim バンドルを使用して、グラデーション背景、インタラクティブなホバーエフェクト、複数のシェイプタイプを備えた設定をゼロから構築します。 + +```html + + + + + + カスタム設定 + + + +

カスタム設定

+
+ + + + + + +``` + +--- + +## 複数コンテナ + +同じページ上で複数の独立したパーティクルインスタンスを、それぞれ独自の設定で実行します。 + +```html + + + + + + 複数コンテナ + + + +
+
+
+
+ + + + + + +``` + +--- + +## 動的コントロール + +プログラムによる開始、停止、一時停止、およびテーマの切り替えを実行時に実行します。 + +```html + + + + + + 動的コントロール + + + +
+
+ + + + + + +
+ + + + + + +``` + +--- + +以上で、tsParticles v4 のすべての主要な Vanilla JS 統合パターンを網羅しました。各サンプルはスタンドアロンの HTML ファイルとして、ブラウザで開けば tsParticles の動作を確認できます。 diff --git a/websites/website/docs/ja/guides/vue3.md b/websites/website/docs/ja/guides/vue3.md new file mode 100644 index 00000000000..b9a4c4f721e --- /dev/null +++ b/websites/website/docs/ja/guides/vue3.md @@ -0,0 +1,622 @@ +--- +title: Vue 3 インテグレーション +description: "@tsparticles/vue3 を使用して tsParticles を Vue 3 アプリケーションに統合するためのステップバイステップガイド。" +--- + +# Vue 3 インテグレーション + +`@tsparticles/vue3` パッケージは、tsParticles のネイティブ Vue 3 コンポーネントとプラグインシステムを提供します。このガイドでは、基本的なセットアップから動的テーマ切り替えやカスタムプリセットなどの高度なパターンまでをカバーします。 + +--- + +## インストール + +```bash +npm install @tsparticles/vue3 @tsparticles/engine +``` + +オプションでプリセットまたは完全なバンドルをインストールします: + +```bash +# 完全バンドル(すべての機能) +npm install tsparticles + +# 特定のプリセット +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars + +# ユーティリティ設定 +npm install @tsparticles/configs +``` + +--- + +## 基本的な使い方 + +アプリのエントリーポイントでプラグインを登録し、その後任意の場所で `` コンポーネントを使用します。 + +### アプリエントリー(`main.ts`) + +```typescript +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +const app = createApp(App); + +app.use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, +}); + +app.mount("#app"); +``` + +### コンポーネント(`App.vue`) + +```vue + + + +``` + +--- + +## コンポーネントでの `particlesInit` の使用 + +グローバルプラグインを使用したくない場合は、`init` コールバックを直接渡します: + +```vue + + + +``` + +--- + +## イベント + +コンポーネントはいくつかのライフサイクルイベントを発行します: + +```vue + + + +``` + +--- + +## クラッカーエフェクト + +お祝いにクラッカープリセットを使用します: + +```bash +npm install @tsparticles/preset-confetti +``` + +```vue + + + +``` + +1回限りのバーストの場合は、プリセットをロードした後、メソッド内でプログラム的に `tsParticles.load()` を呼び出します。 + +--- + +## 花火エフェクト + +花火プリセットはインパクトのあるパーティクル爆発を作成します: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```vue + + + +``` + +> **ヒント:** 花火プリセットはリソースを多く消費します。コンポーネントにバインドした `v-if` を切り替えて、ユーザーインタラクション(例: ボタンクリック)でトリガーしてください。 + +--- + +## 雪エフェクト + +雪プリセットで降雪をシミュレートします: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +--- + +## インタラクティブパーティクル + +ホバーとクリックのインタラクティビティモードを追加します: + +```vue + + + +``` + +利用可能なインタラクションモード: `grab`、`repulse`、`bubble`、`connect`、`push`、`remove`、`trail`、`attract`、`light`。 + +--- + +## テーマ切り替え + +リアクティブな options オブジェクトを更新して、実行時にパーティクルテーマを動的に切り替えます: + +```vue + + + +``` + +または、組み込みの [themes](https://particles.js.org/docs/interfaces/Options_Interfaces_IOptions.IOptions.html#themes) オプションとコンテナの `theme` プロパティを使用して、設定不要の切り替えを実現します。 + +--- + +## @tsparticles/configs のカスタムプリセット + +`@tsparticles/configs` パッケージは、既成の設定オブジェクトをエクスポートします: + +```bash +npm install @tsparticles/configs +``` + +```vue + + + +``` + +`@tsparticles/configs` パッケージで利用可能な設定を参照して、すぐに使えるレイアウトを確認してください。 + +--- + +## エンジン初期化のアプローチ + +エンジンを初期化するには2つの方法があります: + +### 1. グローバルプラグイン(推奨) + +```typescript +// main.ts +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +createApp(App) + .use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, + }) + .mount("#app"); +``` + +エンジンはグローバルに利用可能になり、すべての `` インスタンスがそれを共有します。 + +### 2. コンポーネントレベルの Init + +各 `` インスタンスに `:init` コールバックを渡します。異なるコンポーネントが異なるプラグインセットを必要とする場合に便利です: + +```vue + +``` + +### 3. Particles Provider(Composition API) + +プロバイダーを使用して、プログラム的にエンジンにアクセスします: + +```vue + +``` + +--- + +## 名前付きエクスポート + TypeScript + +すべての要素を組み合わせた完全な TypeScript の例: + +```vue + + + +``` + +--- + +## API リファレンス + +| プロップ | タイプ | デフォルト | 説明 | +| --------- | ----------------------------------- | --------------- | -------------------------- | +| `id` | `string` | `"tsparticles"` | キャンバス要素 ID | +| `options` | `ISourceOptions` | `{}` | パーティクル設定 | +| `init` | `(engine: Engine) => Promise` | — | エンジン初期化コールバック | +| `url` | `string` | — | JSON 設定をロードする URL | + +| イベント | ペイロード | 説明 | +| ------------------- | ----------- | -------------------------------------- | +| `@particles-loaded` | `Container` | コンテナが完全に初期化されたときに発生 | +| `@particles-init` | `Engine` | エンジンが初期化された後に発生 | + +--- + +## トラブルシューティング + +- **エラー: `tsparticles is not defined`** — コンポーネントがレンダリングされる前に、`init` コールバック内で `tsparticles`(または必要なプリセット)がロードされていることを確認してください。 +- **キャンバスが表示されない** — 親コンテナにゼロ以外の高さがあることを確認してください。`#tsparticles { height: 100vh; }` のような CSS ルールを追加します。 +- **パフォーマンスの問題** — ローエンドデバイスでは `fpsLimit` を下げ、`particles.number.value` を減らすか、`detectRetina` を無効にします。 +- **SSR(Nuxt)** — `` コンポーネントはクライアント専用です。`` でラップするか、`client:only` ディレクティブを使用します。 diff --git a/websites/website/docs/ja/guides/webcomponents.md b/websites/website/docs/ja/guides/webcomponents.md new file mode 100644 index 00000000000..8c3232e3f57 --- /dev/null +++ b/websites/website/docs/ja/guides/webcomponents.md @@ -0,0 +1,359 @@ +# Web Components + +`@tsparticles/webcomponents` パッケージを使用して、ネイティブの Web Components で tsParticles を使用します。このアプローチにはフレームワークは不要で、プレーンな JavaScript とカスタム要素のみで動作します。 + +## インストール + +### CDN 経由 + +tsParticles コアと Web Components バンドルをインクルードします: + +```html + + +``` + +### npm + ビルド経由 + +```bash +npm install @tsparticles/webcomponents tsparticles +``` + +次に、JavaScript バンドルにインポートします: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; +``` + +## エンジンの初期化 + +`` 要素がレンダリングできるようになる前に、必要な機能でエンジンを初期化する必要があります。目的のプラグインをロードするコールバックを指定して `initParticlesEngine` を呼び出します: + +```javascript +import { initParticlesEngine } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +> **なぜ `loadFull` なのか?** すべての組み込みシェイプ(円、四角、多角形、画像など)、インタラクション(ホバー、クリック)、アップデーター(不透明度、サイズ、色など)を登録します。より小さなバンドルの場合は、`tsparticles-slim` を使用するか、個別のプラグインを選択してください。 + +## カスタム要素の定義 + +エンジンの初期化後、`` カスタム要素を登録します: + +```javascript +import { defineParticlesElement } from "@tsparticles/webcomponents"; + +defineParticlesElement(); +``` + +これにより、`web-particles` タグがブラウザの `CustomElementRegistry` に登録されます。複数回呼び出しても安全です — 重複した登録は無視されます。 + +## 基本的な使い方 + +`initParticlesEngine` と `defineParticlesElement` の両方が実行されたら、HTML で要素を直接使用します: + +```html + + + + + + tsParticles Web Components + + + + + + + +``` + +## カスタム設定 + +`` 要素は、`options` プロパティ(JavaScript オブジェクト)または `options` 属性の JSON を介して設定を受け入れます。 + +### JavaScript プロパティ経由 + +```javascript +const el = document.querySelector("web-particles"); +el.options = { + background: { color: "#000000" }, + fpsLimit: 60, + particles: { + color: { value: ["#ff0000", "#00ff00", "#0000ff"] }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { value: 60 }, + opacity: { value: 0.6 }, + shape: { type: ["circle", "square"] }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + repulse: { distance: 200 }, + push: { quantity: 4 }, + }, + }, +}; +``` + +### HTML 属性(JSON)経由 + +```html + +``` + +> `options` 属性を使用する場合、値は有効な JSON である必要があります。複雑な設定にはプロパティ割り当てが推奨されます。 + +## 動的な作成 + +`` 要素を完全に JavaScript で作成し、いつでも DOM に追加できます: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +defineParticlesElement(); + +function createParticles(container, config) { + const el = document.createElement("web-particles"); + el.id = "dynamic-particles"; + el.style.position = "absolute"; + el.style.width = "100%"; + el.style.height = "100%"; + el.style.top = "0"; + el.style.left = "0"; + el.options = config; + container.appendChild(el); + return el; +} + +// 使用例 +const particles = createParticles(document.body, { + background: { color: "#1a1a2e" }, + particles: { + number: { value: 100 }, + links: { enable: true, color: "#e94560" }, + move: { enable: true, speed: 1 }, + }, +}); +``` + +## カスタム要素の拡張 + +`ParticlesElement` をサブクラス化して、組み込み設定付きの独自のカスタム要素を作成できます: + +```javascript +import { initParticlesEngine, ParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +class MyParticlesBackground extends ParticlesElement { + constructor() { + super(); + this.style.position = "fixed"; + this.style.top = "0"; + this.style.left = "0"; + this.style.width = "100%"; + this.style.height = "100%"; + this.style.zIndex = "-1"; + } + + connectedCallback() { + this.options = { + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true, speed: 2 }, + }, + }; + super.connectedCallback(); + } +} + +customElements.define("my-particles-bg", MyParticlesBackground); +``` + +使用例: + +```html + +``` + +## コンテナへのアクセスと制御 + +カスタム要素は、命令的な制御のための tsParticles `Container` インスタンスを公開します: + +```javascript +const el = document.querySelector("web-particles"); + +// コンテナへのアクセス(connectedCallback 後に利用可能) +const container = el.container; +container?.pause(); +container?.play(); + +// 破棄してクリーンアップ +el.dispose(); +``` + +## 完全な例 + +CDN スクリプトで Web Components モジュールを使用した完全な HTML ページ: + +```html + + + + + + tsParticles Web Components Demo + + + +
+

tsParticles + Web Components

+

Native custom elements, no framework required.

+
+ + + + + + +``` + +## API リファレンス + +| エクスポート / プロパティ | タイプ | 説明 | +| ------------------------------- | ------------------------ | ---------------------------------------------------------- | +| `initParticlesEngine(callback)` | `function` | プラグインローダーで tsParticles エンジンを初期化します | +| `defineParticlesElement()` | `function` | `` カスタム要素を登録します | +| `ParticlesElement` | `class` | カスタム要素を拡張するための基底クラス | +| `element.options` | `ISourceOptions` | パーティクル設定オブジェクトの取得/設定 | +| `element.container` | `Container \| undefined` | 基礎となる `Container` への読み取り専用参照 | +| `element.dispose()` | `function` | パーティクルインスタンスを破棄してリソースをクリーンアップ | diff --git a/websites/website/docs/ja/guides/wordpress.md b/websites/website/docs/ja/guides/wordpress.md new file mode 100644 index 00000000000..b2a83d68498 --- /dev/null +++ b/websites/website/docs/ja/guides/wordpress.md @@ -0,0 +1,125 @@ +# WordPress + +`@tsparticles/wordpress` パッケージは、WordPress ブログやウェブサイトにパーティクル背景を追加する簡単な方法を提供します。このガイドでは、WordPress 管理者ダッシュボードから直接 tsParticles を設定する手順を説明します。 + +## インストール + +WordPress 管理パネルから tsParticles WordPress プラグインをインストールします: + +1. WordPress ダッシュボードで **プラグイン** > **新規追加** に移動します +2. **"tsParticles"** を検索します +3. **今すぐインストール** をクリックします +4. インストール後、**有効化** をクリックします + +または、プラグインを [WordPress.org プラグインディレクトリ](https://wordpress.org/plugins/tsparticles/) から直接ダウンロードするか、`wp-content/plugins/` ディレクトリに手動でアップロードします。 + +## 設定 + +プラグインを有効化すると、WordPress 管理サイドバーに新しい **tsParticles** メニュー項目が表示されます。ここでパーティクル設定をカスタマイズできます。 + +### 基本的な設定 + +設定ページでは、以下のオプションを提供するフォームが表示されます: + +- **有効/無効**: サイト全体でパーティクルをオンまたはオフにします +- **背景色**: パーティクルキャンバスの背景色 +- **パーティクル色**: パーティクルの色 +- **パーティクル数**: 表示するパーティクルの数 +- **接続線を有効化**: 近くのパーティクル間に線を描画します +- **接続線の色**: 接続線の色 +- **パーティクル速度**: パーティクルの移動速度 +- **インタラクション**: ホバー/クリック時の動作(なし、吸着、反発) + +### カスタム JSON 設定 + +上級ユーザーは、カスタム JSON 設定を直接エディターフィールドに貼り付けることができます。これにより、tsParticles が提供するすべての設定オプションを完全に制御できます。 + +```json +{ + "background": { + "color": "#0d47a1" + }, + "particles": { + "number": { + "value": 100 + }, + "color": { + "value": "#ffffff" + }, + "links": { + "enable": true, + "color": "#ffffff" + }, + "move": { + "enable": true, + "speed": 2 + } + } +} +``` + +## ページ固有のコントロール + +ショートコードを使用して、特定のページや投稿でパーティクルを制御することもできます: + +``` +[tsparticles] +``` + +パーティクルを特定の投稿やページに制限するには、次の構文を使用します: + +``` +[tsparticles id="my-particles" options='{"background":{"color":"#000"}}'] +``` + +### ショートコードパラメータ + +| パラメータ | タイプ | デフォルト | 説明 | +| ---------- | -------- | ------------- | ------------------------------------------- | +| `id` | `string` | `tsparticles` | キャンバス要素 ID | +| `class` | `string` | `""` | 追加の CSS クラス | +| `style` | `string` | `""` | インラインスタイル | +| `options` | `string` | `""` | JSON 設定オブジェクト(引用符をエスケープ) | + +## テーマの統合 + +プラグインは最新の WordPress テーマと互換性があります。FSE(フルサイト編集)テーマでは、テンプレートエディターからブロックを直接追加できます: + +1. **外観** > **エディター** に移動します +2. テンプレートを編集するか、新しいテンプレートを作成します +3. **+** ボタンをクリックし、"tsParticles" ブロックを検索します +4. ブロックサイドバーから設定を調整します + +## Cache プラグインとの互換性 + +tsParticles WordPress プラグインは、W3 Total Cache、WP Super Cache、WP Rocket などの一般的なキャッシュプラグインと連携して動作するように設計されています。スクリプトはキューに適切に登録されるため、キャッシュ環境でも期待通りに読み込まれ、実行されます。 + +## コンフリクトのトラブルシューティング + +- **jQuery のコンフリクト**: tsParticles は依存関係として jQuery を必要としません。他のスクリプトとの互換性の問題は、サイトのキャッシュをクリアすることで解決できます。 +- **テーマのコンフリクト**: 一部のテーマはパーティクルキャンバスの `z-index` と競合する場合があります。tsParticles 設定でカスタム `z-index` 値を指定するか、テーマの CSS を調整してください。 +- **スクリプトの読み込み順序**: プラグインが他の JavaScript の前に tsParticles を読み込むようにするには、「フッターにスクリプトを読み込む」設定を無効にします。 + +## プラグインの削除 + +tsParticles プラグインをアンインストールするには: + +1. WordPress ダッシュボードで **プラグイン** > **インストール済みプラグイン** に移動します +2. tsParticles を見つけて **無効化** をクリックします +3. 無効化後、**削除** リンクをクリックします + +プラグインを削除しても、サイトのフロントエンドに残ったパーティクルデータは残りません。 + +## よくある質問 + +**tsParticles はモバイルデバイスで動作しますか?** + +はい。パフォーマンスを重視したモバイル設定が自動的に適用されます。必要に応じて管理設定から微調整できます。 + +**パーティクルが表示されません。何が問題ですか?** + +表示されているコンテンツの上にパーティクルキャンバスが正しく配置されていることを確認してください。キャンバスに高さが設定されていない場合、パーティクルは表示されません。CSS で `min-height: 100vh` を設定するか、テーマのコンテナスタイルを確認してください。 + +**管理ページで tsParticles を使用できますか?** + +デフォルトでは、tsParticles は一般ユーザー向けのページでのみ有効です。管理画面での使用は、`tsparticles_admin_enabled` フィルターを使用して有効にできます。 diff --git a/websites/website/docs/options/plugin-colors.md b/websites/website/docs/options/plugin-colors.md index db66b36932c..010c7770ca2 100644 --- a/websites/website/docs/options/plugin-colors.md +++ b/websites/website/docs/options/plugin-colors.md @@ -20,7 +20,7 @@ ## Notes - Load the desired color space plugin to enable its notation. -- Used through the standard `particles.color` options. +- Used through `particles.paint.fill.color` and other color options throughout tsParticles. ## Source reference diff --git a/websites/website/docs/pt/guide/bundles-all.md b/websites/website/docs/pt/guide/bundles-all.md index e0d3e5d9634..df98691b174 100644 --- a/websites/website/docs/pt/guide/bundles-all.md +++ b/websites/website/docs/pt/guide/bundles-all.md @@ -1,21 +1,42 @@ # Bundle: All -`@tsparticles/all` carrega todos os recursos oficiais e e ideal para prototipagem rapida. +`@tsparticles/all` carrega **tudo** do repositório tsParticles: todas as formas, interações, atualizadores, efeitos, caminhos, easings, plugins e exportações. É o maior bundle, destinado à prototipagem e demonstrações. -## Quando escolher All +## Funcionalidades incluídas -- Voce quer todos os recursos disponiveis imediatamente. -- Voce esta explorando opcoes rapidamente. -- O tamanho do bundle e menos importante que a velocidade do setup. +Herda tudo de `tsparticles` (full) mais: -## Instalacao +**Todas as formas:** seta, cartas, engrenagem, coração, infinito, matrix, caminho, ribbon, polígono arredondado, retângulo arredondado, espiral, squircle + +**Todas as interações externas:** cannon, light, particle, pop, particles-repulse + +**Todos os efeitos:** bolha, filtro, partículas, sombra, trail + +**Todos os geradores de caminho:** branches, brownian, curl-noise, curves, fractal-noise, grid, levy, perlin-noise, polygon, random, simplex-noise, spiral, svg, zig-zag + +**Todos os easings:** back, bounce, circ, cubic, elastic, expo, gaussian, linear, quad, quart, quint, sigmoid, sine, smoothstep + +**Todos os plugins de cor:** HEX, HSL, RGB, HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH + +**Todos os plugins:** absorvedores, background-mask, canvas-mask, emissores (todas as formas), easings (todos), export-image, export-json, export-video, infection, manual-particles, motion, poisson-disc, polygon-mask, responsive, sounds, themes, trail, zoom + +**Todos os atualizadores:** destroy, gradient, life, opacity, orbit, out-modes, paint, roll, rotate, size, tilt, twinkle, wobble + +## Quando usar + +- Prototipagem rápida para explorar possibilidades +- Demonstrações e showcases +- Ambientes de desenvolvimento onde o tamanho não importa +- **Não recomendado para produção** — prefira bundles mais específicos + +## Instalação + +### npm/pnpm/yarn ```bash pnpm add @tsparticles/engine @tsparticles/all ``` -## Exemplo de configuracao - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadAll } from "@tsparticles/all"; @@ -25,20 +46,48 @@ await loadAll(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { number: { value: 100 }, + shape: { type: "heart" }, move: { enable: true, speed: 2 }, }, }, }); ``` -## Armadilhas comuns +### CDN (script tags) + +```html + + + +``` + +## Diferença entre `tsparticles` e `@tsparticles/all` + +Consulte a tabela de comparação na [página bundles-full](/pt/guide/bundles-full) para a análise detalhada. + +## Erros comuns -- Usar em producao quando um bundle menor e focado seria melhor. -- Chamar `tsParticles.load(...)` antes de `loadAll(...)`. +- Usar em produção — prefira `@tsparticles/slim` ou `tsparticles` para bundles menores. +- Chamar `tsParticles.load()` antes de `loadAll(tsParticles)`. -## Paginas relacionadas +## Veja também -- Visao geral: [`/guide/bundles`](/pt/guide/bundles) -- Matriz de instalacao: [`/guide/installation`](/pt/guide/installation) +- [Visão geral de bundles](/pt/guide/bundles) +- [Guia de instalação](/pt/guide/installation) diff --git a/websites/website/docs/pt/guide/bundles-basic.md b/websites/website/docs/pt/guide/bundles-basic.md index 518a152abe9..747c2489b53 100644 --- a/websites/website/docs/pt/guide/bundles-basic.md +++ b/websites/website/docs/pt/guide/bundles-basic.md @@ -1,21 +1,46 @@ # Bundle: Basic -`@tsparticles/basic` e voltado para setups extra leves com runtime minimo. +`@tsparticles/basic` é o bundle mais leve. Inclui apenas o essencial: círculos que se movem com opacidade e tamanho animáveis. -## Quando escolher Basic +## Funcionalidades incluídas -- Tamanho do bundle e a prioridade principal. -- Voce precisa apenas de efeitos basicos. -- Plugins avancados nao sao necessarios. +**Formas:** círculo -## Instalacao +**Atualizadores:** + +- paint (cor) +- opacidade +- out-modes (comportamento ao sair da tela) +- tamanho + +**Plugins:** + +- move +- blend (mesclagem de cores) +- Plugins de cor HEX, HSL, RGB + +**Não incluídos:** + +- Interações com mouse/toque +- Links entre partículas +- Outras formas (quadrados, estrelas, imagens, polígonos, etc.) +- Emissores, absorvedores, sons +- Rotação, vida, roll, tilt, wobble + +## Quando usar + +- O tamanho do bundle é sua prioridade máxima +- Você só precisa de pontos se movendo +- Sem interações ou formas complexas necessárias + +## Instalação + +### npm/pnpm/yarn ```bash pnpm add @tsparticles/engine @tsparticles/basic ``` -## Exemplo de configuracao - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadBasic } from "@tsparticles/basic"; @@ -25,20 +50,48 @@ await loadBasic(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#ffffff" }, particles: { number: { value: 50 }, - move: { enable: true, speed: 1.5 }, + color: { value: ["#5bc0eb", "#fde74c", "#9bc53d"] }, + size: { + value: { min: 300, max: 400 }, + animation: { enable: true, speed: 100 }, + }, + move: { enable: true, speed: 10 }, }, }, }); ``` -## Armadilhas comuns +### CDN (script tags) + +```html + + + +``` + +## Erros comuns -- Esperar recursos que pertencem a plugins nao incluidos. -- Chamar `tsParticles.load(...)` antes de `loadBasic(...)`. +- Esperar funcionalidades não incluídas (ex.: `links`, interações com mouse) — estas exigem bundles superiores. +- Chamar `tsParticles.load()` antes de `loadBasic(tsParticles)` — formas e atualizadores ainda não foram registrados. +- Instalar apenas `@tsparticles/engine` sem um bundle — o motor sozinho não desenha nada. -## Paginas relacionadas +## Veja também -- Visao geral: [`/guide/bundles`](/pt/guide/bundles) -- Matriz de instalacao: [`/guide/installation`](/pt/guide/installation) +- [Visão geral de bundles](/pt/guide/bundles) +- [Guia de instalação](/pt/guide/installation) diff --git a/websites/website/docs/pt/guide/bundles-confetti.md b/websites/website/docs/pt/guide/bundles-confetti.md index af2a775abb9..c347d6c71ff 100644 --- a/websites/website/docs/pt/guide/bundles-confetti.md +++ b/websites/website/docs/pt/guide/bundles-confetti.md @@ -1,42 +1,83 @@ # Bundle: Confetti -`@tsparticles/confetti` expoe uma API focada para efeitos de confete com setup minimo. +`@tsparticles/confetti` fornece uma API simplificada para criar efeitos de confete com uma única chamada de função. Sem necessidade de interagir diretamente com `tsParticles`. -## Quando escolher Confetti +## Funcionalidades incluídas -- Voce quer efeitos de celebracao com uma chamada. -- Voce nao precisa fazer wiring manual do engine. -- Voce prefere uma API compacta para eventos de UI. +**Formas:** círculo, coração, cartas (naipes franceses: copas, ouros, paus, espadas), emoji, imagens, polígono, quadrado, estrela -## Instalacao +**Plugins internos:** emissores, motion (respeita a preferência de movimento reduzido do usuário) + +**Atualizadores:** life, roll, rotate, tilt, wobble + +**API:** `confetti(options)` ou `confetti(canvasId, options)` + +## Quando usar + +- Botão "Parabéns!" ou "Feliz Aniversário!" +- Efeito de celebração rápido +- Você não quer configurar o motor manualmente + +## Instalação + +### npm/pnpm/yarn ```bash pnpm add @tsparticles/confetti ``` -## Exemplo de configuracao - ```ts import { confetti } from "@tsparticles/confetti"; +// Efeito básico await confetti({ - count: 80, - spread: 60, + particleCount: 100, + spread: 70, + origin: { x: 0.5, y: 0.5 }, }); -await confetti("canvas-id", { - count: 50, +// Em um canvas específico +await confetti("my-canvas-id", { + particleCount: 50, angle: 90, spread: 45, + colors: ["#ff0000", "#00ff00", "#0000ff"], }); ``` -## Armadilhas comuns +### CDN (script tag) + +```html + + +``` + +### Principais parâmetros + +| Parâmetro | Tipo | Padrão | Descrição | +| --------------- | -------- | ------------ | ---------------------------------------------------- | +| `particleCount` | number | 50 | Número de peças de confete | +| `spread` | number | 60 | Ângulo de dispersão (graus) | +| `angle` | number | 90 | Direção (graus, 90 = para baixo) | +| `startVelocity` | number | 30 | Velocidade inicial | +| `colors` | string[] | — | Cores do confete | +| `origin` | { x, y } | { 0.5, 0.5 } | Ponto de origem (0-1) | +| `drift` | number | 0 | Deriva horizontal | +| `shapes` | string[] | — | Formas: "circle", "heart", "square", "star", "cards" | + +## Erros comuns -- Assumir que `tsParticles` e exportado por `@tsparticles/confetti`. -- Reutilizar o mesmo id de canvas sem querer. +- Pensar que `tsParticles` é exportado por `@tsparticles/confetti` — não é. +- Reutilizar o mesmo ID de canvas sem intenção. +- Chamar `confetti` em um loop sem gerenciar performance — use um intervalo razoável ou pare a animação quando terminar. -## Paginas relacionadas +## Veja também -- Visao geral: [`/guide/bundles`](/pt/guide/bundles) -- Bundles no playground: [`/playground/bundles`](/pt/playground/bundles) +- [Visão geral de bundles](/pt/guide/bundles) +- [Bundle Fireworks](/pt/guide/bundles-fireworks) diff --git a/websites/website/docs/pt/guide/bundles-fireworks.md b/websites/website/docs/pt/guide/bundles-fireworks.md index 9c2e81da66d..e4c5154d408 100644 --- a/websites/website/docs/pt/guide/bundles-fireworks.md +++ b/websites/website/docs/pt/guide/bundles-fireworks.md @@ -1,44 +1,81 @@ # Bundle: Fireworks -`@tsparticles/fireworks` expoe uma API focada para efeitos de fogos de artificio com setup minimo. +`@tsparticles/fireworks` fornece uma API simplificada para criar efeitos de fogos de artifício com uma única chamada de função. Suporta sons, cores personalizadas e controle de instância (pausar/reproduzir). -## Quando escolher Fireworks +## Funcionalidades incluídas -- Voce quer animacoes fireworks com uma chamada. -- Voce nao precisa de wiring direto do engine. -- Voce prefere uma API compacta para momentos de celebracao. +**Formas:** linha, círculo (do basic) -## Instalacao +**Plugins internos:** emissores, emitters-shape-square, blend (mesclagem), sons + +**Atualizadores:** destroy, life, paint, rotate + +**API:** `fireworks(options)` — retorna uma instância controlável + +## Quando usar + +- Efeito de Ano Novo ou celebração +- UI de celebração +- Você não quer configurar o motor manualmente + +## Instalação + +### npm/pnpm/yarn ```bash pnpm add @tsparticles/fireworks ``` -## Exemplo de configuracao - ```ts import { fireworks } from "@tsparticles/fireworks"; +// Efeito básico const instance = await fireworks({ - colors: ["#ffffff", "#ff0000"], - sounds: false, + colors: ["#ffffff", "#ff0000", "#00ff00", "#0000ff"], + sounds: true, }); +// Controle de instância instance?.pause(); instance?.play(); -await fireworks("canvas-id", { +// Em um canvas específico +await fireworks("my-canvas", { rate: 3, speed: { min: 10, max: 25 }, + sounds: false, }); ``` -## Armadilhas comuns +### CDN (script tag) + +```html + + +``` + +### Principais parâmetros + +| Parâmetro | Tipo | Padrão | Descrição | +| ------------ | ------------ | ------ | ------------------------- | +| `colors` | string[] | — | Cores da explosão | +| `rate` | number | — | Fogos por segundo | +| `speed` | { min, max } | — | Velocidade das partículas | +| `sounds` | boolean | true | Ativar efeitos sonoros | +| `gravity` | number | — | Gravidade (padrão: 0) | +| `opacity` | number | — | Opacidade (0-1) | +| `brightness` | { min, max } | — | Brilho da explosão | + +## Erros comuns -- Assumir que `tsParticles` e exportado por `@tsparticles/fireworks`. -- Chamar `fireworks(...)` repetidamente sem gerenciar a instancia. +- Pensar que `tsParticles` é exportado por `@tsparticles/fireworks` — não é. +- Chamar `fireworks()` em um loop sem gerenciar a instância — o efeito já é contínuo. +- Não parar a instância ao sair da página — chame `instance?.pause()` ou `instance?.stop()`. -## Paginas relacionadas +## Veja também -- Visao geral: [`/guide/bundles`](/pt/guide/bundles) -- Bundles no playground: [`/playground/bundles`](/pt/playground/bundles) +- [Visão geral de bundles](/pt/guide/bundles) +- [Bundle Confetti](/pt/guide/bundles-confetti) diff --git a/websites/website/docs/pt/guide/bundles-full.md b/websites/website/docs/pt/guide/bundles-full.md index 34c60238bdc..baa6cbe2048 100644 --- a/websites/website/docs/pt/guide/bundles-full.md +++ b/websites/website/docs/pt/guide/bundles-full.md @@ -1,21 +1,48 @@ # Bundle: tsparticles (Full) -`tsparticles` e o bundle full e inclui um conjunto amplo de recursos oficiais com um unico loader. +`tsparticles` (npm: `tsparticles`, loader: `loadFull`) é o bundle completo oficial. Inclui tudo do Slim mais emissores, absorvedores, formas de texto e animações avançadas (wobble, roll, tilt, twinkle, destroy). -## Quando escolher tsparticles (Full) +## Funcionalidades incluídas -- Voce precisa de muitos recursos oficiais sem selecionar plugins manualmente. -- Voce quer uma base completa pronta para producao antes de ajustar. -- Voce prefere controle do engine pela API `tsParticles`. +Herda tudo de `@tsparticles/slim` mais: -## Instalacao +**Formas adicionais:** texto (com fontes personalizadas) + +**Interações externas adicionais:** + +- drag (arrastar partículas com o mouse) +- trail (rastro de partículas atrás do mouse) + +**Atualizadores adicionais:** + +- destroy (animação de destruição de partículas) +- roll (rolamento) +- tilt (inclinação 3D) +- twinkle (brilho intermitente) +- wobble (oscilação) + +**Plugins:** + +- absorbers (buracos negros que sugam partículas) +- emitters (fontes contínuas de partículas) +- emitters-shape-circle, emitters-shape-square (formas de emissores) + +## Quando usar + +- Precisa de emissores (partículas gerando continuamente) +- Precisa de absorvedores (partículas sendo sugadas) +- Precisa de formas de texto com fontes personalizadas +- Precisa de animações avançadas (wobble, tilt, roll, twinkle) +- Bom passo intermediário antes de ir para plugins individuais + +## Instalação + +### npm/pnpm/yarn ```bash pnpm add @tsparticles/engine tsparticles ``` -## Exemplo de setup - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadFull } from "tsparticles"; @@ -25,20 +52,65 @@ await loadFull(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { - number: { value: 100 }, - move: { enable: true, speed: 2 }, + number: { value: 50 }, + shape: { type: "text", options: { text: ["🔥", "✨", "⭐"] } }, + size: { value: 24 }, + move: { enable: true, speed: 1 }, + wobble: { enable: true, distance: 10 }, + }, + emitters: { + direction: "top", + rate: { quantity: 2, delay: 0.3 }, }, }, }); ``` +### CDN (script tags) + +```html + + + +``` + +## Diferença entre `tsparticles` e `@tsparticles/all` + +| Aspecto | `tsparticles` (full) | `@tsparticles/all` | +| -------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | +| Tamanho | Moderado | Muito grande | +| Formas | círculo, quadrado, estrela, polígono, linha, imagem, emoji, texto | Todas as formas (coração, cartas, seta, espiral, engrenagem, retângulo arredondado, etc.) | +| Interações | Slim + drag + trail | Todas (cannon, light, pop, particle, repulse) | +| Caminhos | Apenas easing quad | 14 geradores de caminho | +| Efeitos | Nenhum | 5 efeitos (bolha, filtro, sombra, etc.) | +| Exportações | Nenhuma | Imagem, JSON, Vídeo | +| Plugins extras | absorvedores, emissores | Todos (sons, temas, trail, zoom, polygon-mask, canvas-mask, background-mask, etc.) | +| Easing | Quad | 15 easings | + ## Erros comuns -- Chamar `tsParticles.load(...)` antes de `loadFull(...)`. -- Assumir que e o mesmo pacote que `@tsparticles/all` (sao bundles diferentes). +- Confundir `tsparticles` com `@tsparticles/all` — são pacotes diferentes. +- Chamar `tsParticles.load()` antes de `loadFull(tsParticles)`. +- O pacote npm é `tsparticles` (não `@tsparticles/full`), o loader é `loadFull`. -## Paginas relacionadas +## Veja também -- Visao geral: [`/guide/bundles`](/pt/guide/bundles) -- Matriz de instalacao: [`/guide/installation`](/pt/guide/installation) +- [Visão geral de bundles](/pt/guide/bundles) +- [Guia de instalação](/pt/guide/installation) diff --git a/websites/website/docs/pt/guide/bundles-particles.md b/websites/website/docs/pt/guide/bundles-particles.md index 096cd6e051a..98fdceb2e8f 100644 --- a/websites/website/docs/pt/guide/bundles-particles.md +++ b/websites/website/docs/pt/guide/bundles-particles.md @@ -1,42 +1,98 @@ # Bundle: Particles -`@tsparticles/particles` expoe uma API focada para fundos de particulas simples. +`@tsparticles/particles` fornece uma API simplificada para criar fundos de partículas interativos. Uma alternativa mais rica a `@tsparticles/basic` com uma API dedicada em vez de configuração manual do motor. -## Quando escolher Particles +## Funcionalidades incluídas -- Voce quer uma API rapida para fundos de particulas. -- Voce nao precisa configurar engine/plugins manualmente. -- Voce prefere uma API compacta em estilo app. +**Formas:** círculo (do basic) -## Instalacao +**Plugins internos:** interatividade (links, colisões) + +**Interações:** links (conexões entre partículas), colisões + +**API:** `particles(options)` ou `particles(canvasId, options)` + +## Quando usar + +- Fundo de partículas para um site +- Fundo com links entre partículas (efeito estilo nó) +- Você não quer configurar o motor manualmente + +## Instalação + +### npm/pnpm/yarn ```bash pnpm add @tsparticles/particles ``` -## Exemplo de configuracao - ```ts import { particles } from "@tsparticles/particles"; +// Fundo com links await particles({ count: 120, links: true, - linksColor: "#0ff", + color: "#ffffff", + linksColor: "#00d8ff", + radius: 3, + speed: 2, + opacity: 0.8, }); -await particles("canvas-id", { +// Em um canvas específico +await particles("my-canvas", { count: 80, shape: ["circle", "square"], + links: true, }); + +// Com cores personalizadas +await particles({ + count: 100, + color: ["#ff6b6b", "#4ecdc4", "#45b7d1"], + links: false, +}); +``` + +### CDN (script tag) + +```html + + ``` -## Armadilhas comuns +### Principais parâmetros + +| Parâmetro | Tipo | Padrão | Descrição | +| ------------ | ------------------ | ---------- | ----------------------- | +| `count` | number | 50 | Número de partículas | +| `radius` | number | 3 | Raio das partículas | +| `speed` | number | 2 | Velocidade de movimento | +| `opacity` | number | 0.8 | Opacidade (0-1) | +| `color` | string \| string[] | "#ffffff" | Cor(es) das partículas | +| `links` | boolean | false | Mostrar links | +| `linksColor` | string | "#ffffff" | Cor dos links | +| `linksWidth` | number | 1 | Espessura dos links | +| `shape` | string[] | ["circle"] | Formas das partículas | + +## Erros comuns -- Assumir que `tsParticles` e exportado por `@tsparticles/particles`. -- Reutilizar o mesmo id de canvas sem querer. +- Pensar que `tsParticles` é exportado por `@tsparticles/particles` — não é. +- Reutilizar o mesmo ID de canvas sem intenção. +- Esperar formas avançadas (estrelas, polígonos) — o bundle particles é baseado no basic e usa apenas círculos. -## Paginas relacionadas +## Veja também -- Visao geral: [`/guide/bundles`](/pt/guide/bundles) -- Bundles no playground: [`/playground/bundles`](/pt/playground/bundles) +- [Visão geral de bundles](/pt/guide/bundles) +- [Primeiros passos](/pt/guide/getting-started) diff --git a/websites/website/docs/pt/guide/bundles-slim.md b/websites/website/docs/pt/guide/bundles-slim.md index 304c2c2f210..bffde8f7b1d 100644 --- a/websites/website/docs/pt/guide/bundles-slim.md +++ b/websites/website/docs/pt/guide/bundles-slim.md @@ -1,21 +1,61 @@ # Bundle: Slim -`@tsparticles/slim` e a escolha recomendada para a maioria dos projetos. +`@tsparticles/slim` é o bundle recomendado para a maioria dos projetos. Inclui tudo o que é necessário para animações de partículas modernas com interações de mouse, múltiplas formas e links entre partículas. -## Quando escolher Slim +## Funcionalidades incluídas -- Voce quer bom equilibrio entre tamanho e recursos. -- Voce usa a API de engine `tsParticles` diretamente. -- Voce precisa de formas/interacoes comuns sem carregar tudo. +Herda tudo de `@tsparticles/basic` mais: -## Instalacao +**Formas:** círculo, quadrado, estrela, polígono, linha, imagem, emoji + +**Interações externas (mouse/toque):** + +- attract +- bounce +- bubble +- connect +- destroy +- grab +- parallax +- pause +- push +- remove +- repulse +- slow + +**Interações entre partículas:** + +- attract +- colisões +- links (conexões entre partículas) + +**Atualizadores adicionais:** + +- life (ciclo de vida) +- rotate + +**Plugins:** + +- interatividade +- easing-quad +- Plugins de cor HEX, HSL, RGB + +## Quando usar + +- Ponto de partida recomendado para a maioria dos projetos +- Precisa de múltiplas formas (círculos, estrelas, polígonos, imagens) +- Precisa de interações com mouse (clique, passar, bubble, repulse) +- Precisa de links entre partículas +- Bom equilíbrio entre tamanho do bundle e funcionalidades + +## Instalação + +### npm/pnpm/yarn ```bash pnpm add @tsparticles/engine @tsparticles/slim ``` -## Exemplo de configuracao - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; @@ -25,21 +65,47 @@ await loadSlim(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#0b1020" }, particles: { number: { value: 80 }, + links: { enable: true, distance: 150 }, move: { enable: true, speed: 2 }, - links: { enable: true }, + shape: { type: ["circle", "star", "square"] }, }, }, }); ``` -## Armadilhas comuns +### CDN (script tags) + +```html + + + +``` + +## Erros comuns -- Chamar `tsParticles.load(...)` antes de `loadSlim(...)`. -- Misturar versoes entre engine e plugins. +- Chamar `tsParticles.load()` antes de `loadSlim(tsParticles)`. +- Misturar versões diferentes entre o motor e o bundle — mantenha-os alinhados. +- Esperar funcionalidades de bundles superiores (emissores, absorvedores, texto, wobble) — precisa de `tsparticles` (full) ou plugins individuais. -## Paginas relacionadas +## Veja também -- Visao geral: [`/guide/bundles`](/pt/guide/bundles) -- Matriz de instalacao: [`/guide/installation`](/pt/guide/installation) +- [Visão geral de bundles](/pt/guide/bundles) +- [Guia de instalação](/pt/guide/installation) diff --git a/websites/website/docs/pt/guide/bundles.md b/websites/website/docs/pt/guide/bundles.md index 8428087a674..4b809c35955 100644 --- a/websites/website/docs/pt/guide/bundles.md +++ b/websites/website/docs/pt/guide/bundles.md @@ -1,104 +1,184 @@ # Guia de bundles -Esta pagina ajuda voce a escolher o bundle certo do `tsParticles` e configurar tudo rapidamente. - -## Comparacao de pacotes - -| Pacote | Ideal para | Estilo de setup | -| ------------------------ | ------------------------------------------------------------- | ---------------------------------------------- | -| `@tsparticles/basic` | Configuracoes super leves | `tsParticles` + `await loadBasic(tsParticles)` | -| `@tsparticles/slim` | A maioria dos sites/apps | `tsParticles` + `await loadSlim(tsParticles)` | -| `tsparticles` | Conjunto completo de recursos oficiais com controle do engine | `tsParticles` + `await loadFull(tsParticles)` | -| `@tsparticles/all` | Todos os recursos, prototipagem rapida | `tsParticles` + `await loadAll(tsParticles)` | -| `@tsparticles/confetti` | Efeitos de confete com uma chamada | `await confetti(options)` | -| `@tsparticles/fireworks` | Efeitos de fogos com uma chamada | `await fireworks(options)` | -| `@tsparticles/particles` | API simples para fundo de particulas | `await particles(options)` | -| `@tsparticles/ribbons` | Efeitos de ribbons com uma chamada | `await ribbons(options)` | - -## Guias por bundle - -- Basic: [`/guide/bundles-basic`](/pt/guide/bundles-basic) -- Slim: [`/guide/bundles-slim`](/pt/guide/bundles-slim) -- tsparticles (Full): [`/guide/bundles-full`](/pt/guide/bundles-full) -- All: [`/guide/bundles-all`](/pt/guide/bundles-all) -- Confetti: [`/guide/bundles-confetti`](/pt/guide/bundles-confetti) -- Fireworks: [`/guide/bundles-fireworks`](/pt/guide/bundles-fireworks) -- Particles: [`/guide/bundles-particles`](/pt/guide/bundles-particles) -- Ribbons (demo + docs): [`/demos/recipes/ribbons`](/pt/demos/recipes/ribbons) · - -## Instalacao - -Instale o caminho de pacote que combina com seu caso de uso. - -```bash -pnpm add @tsparticles/engine @tsparticles/basic -pnpm add @tsparticles/engine @tsparticles/slim -pnpm add @tsparticles/engine tsparticles -pnpm add @tsparticles/engine @tsparticles/all -pnpm add @tsparticles/confetti -pnpm add @tsparticles/fireworks -pnpm add @tsparticles/particles -pnpm add @tsparticles/ribbons +O tsParticles é modular. O pacote `@tsparticles/engine` contém apenas o núcleo do motor; para obter efeitos visíveis você deve registrar **formas** (o que desenhar), **atualizadores** (como animar), **interações** (como reagir ao mouse/toque) e **plugins** (funcionalidades extras). Tudo isso acontece através de **bundles**. + +## Categorias de bundles + +| Categoria | Bundle | API | +| -------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------- | +| Motor + loader | `@tsparticles/basic`, `@tsparticles/slim`, `tsparticles`, `@tsparticles/all` | `tsParticles.load({ id, options })` | +| API dedicada | `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles`, `@tsparticles/ribbons` | `confetti({...})`, `fireworks({...})`, etc. | + +## Comparação completa de funcionalidades + +Legenda: ● = incluído, ○ = não incluído + +| Funcionalidade | basic | slim | full (`tsparticles`) | all | +| --------------------------------------------------------------------------------------------------- | ----- | ---- | -------------------- | ---------------- | +| **Formas** | | | | | +| Círculo | ● | ● | ● | ● | +| Quadrado | ○ | ● | ● | ● | +| Estrela | ○ | ● | ● | ● | +| Polígono | ○ | ● | ● | ● | +| Linha | ○ | ● | ● | ● | +| Imagem | ○ | ● | ● | ● | +| Emoji | ○ | ● | ● | ● | +| Texto | ○ | ○ | ● | ● | +| Cartas (naipes) | ○ | ○ | ○ | ● | +| Coração | ○ | ○ | ○ | ● | +| Seta | ○ | ○ | ○ | ● | +| Retângulo arredondado | ○ | ○ | ○ | ● | +| Polígono arredondado | ○ | ○ | ○ | ● | +| Espiral | ○ | ○ | ○ | ● | +| Squircle | ○ | ○ | ○ | ● | +| Engrenagem | ○ | ○ | ○ | ● | +| Infinito | ○ | ○ | ○ | ● | +| Matrix | ○ | ○ | ○ | ● | +| Caminho | ○ | ○ | ○ | ● | +| Ribbon | ○ | ○ | ○ | ● | +| **Interações externas (mouse/toque)** | | | | | +| Attract | ○ | ● | ● | ● | +| Bounce | ○ | ● | ● | ● | +| Bubble | ○ | ● | ● | ● | +| Connect | ○ | ● | ● | ● | +| Destroy | ○ | ● | ● | ● | +| Grab | ○ | ● | ● | ● | +| Parallax | ○ | ● | ● | ● | +| Pause | ○ | ● | ● | ● | +| Push | ○ | ● | ● | ● | +| Remove | ○ | ● | ● | ● | +| Repulse | ○ | ● | ● | ● | +| Slow | ○ | ● | ● | ● | +| Drag | ○ | ○ | ● | ● | +| Trail | ○ | ○ | ● | ● | +| Cannon | ○ | ○ | ○ | ● | +| Particle | ○ | ○ | ○ | ● | +| Pop | ○ | ○ | ○ | ● | +| Light | ○ | ○ | ○ | ● | +| **Interações entre partículas** | | | | | +| Links | ○ | ● | ● | ● | +| Colisões | ○ | ● | ● | ● | +| Attract | ○ | ● | ● | ● | +| Repulse | ○ | ○ | ○ | ● | +| **Atualizadores (animações)** | | | | | +| Opacidade | ● | ● | ● | ● | +| Tamanho | ● | ● | ● | ● | +| Modos de saída | ● | ● | ● | ● | +| Pintura (cor) | ● | ● | ● | ● | +| Rotação | ○ | ● | ● | ● | +| Vida | ○ | ● | ● | ● | +| Destroy | ○ | ○ | ● | ● | +| Roll | ○ | ○ | ● | ● | +| Tilt | ○ | ○ | ● | ● | +| Twinkle | ○ | ○ | ● | ● | +| Wobble | ○ | ○ | ● | ● | +| Gradiente | ○ | ○ | ○ | ● | +| Órbita | ○ | ○ | ○ | ● | +| **Plugins** | | | | | +| Movimento | ● | ● | ● | ● | +| Blend | ● | ● | ● | ● | +| Emissores | ○ | ○ | ● | ● | +| Absorvedores | ○ | ○ | ● | ● | +| Sons | ○ | ○ | ○ | ● | +| Motion (preferências do usuário) | ○ | ○ | ○ | ● | +| Temas | ○ | ○ | ○ | ● | +| Máscara de polígono | ○ | ○ | ○ | ● | +| Máscara de canvas | ○ | ○ | ○ | ● | +| Máscara de fundo | ○ | ○ | ○ | ● | +| Exportação (imagem, json, vídeo) | ○ | ○ | ○ | ● | +| Partículas manuais | ○ | ○ | ○ | ● | +| Responsivo | ○ | ○ | ○ | ● | +| Trail | ○ | ○ | ○ | ● | +| Zoom | ○ | ○ | ○ | ● | +| Poisson disc | ○ | ○ | ○ | ● | +| **Caminhos** | | | | | +| Qualquer caminho | ○ | ○ | ○ | ● (14 geradores) | +| **Efeitos** | | | | | +| Bolha, Filtro, Sombra, etc. | ○ | ○ | ○ | ● (5 efeitos) | +| **Easing** | | | | | +| Quad | ○ | ● | ● | ● | +| Back, Bounce, Circ, Cubic, Elastic, Expo, Gaussian, Linear, Quart, Quint, Sigmoid, Sine, Smoothstep | ○ | ○ | ○ | ● | +| **Plugins de cor** | | | | | +| HEX, HSL, RGB | ● | ● | ● | ● | +| HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH | ○ | ○ | ○ | ● | + +### Bundles com API dedicada + +| Funcionalidade | confetti | fireworks | particles | ribbons | +| ----------------- | -------------------------------------------------------------------- | ---------------------- | ----------------- | ----------------- | +| Formas | círculo, coração, cartas, emoji, imagem, polígono, quadrado, estrela | linha | (do basic) | ribbon | +| Interações | — | — | links + colisões | — | +| Plugins especiais | emissores, motion | emissores, sons, blend | — | emissores, motion | +| Chamada de API | `confetti(opts)` | `fireworks(opts)` | `particles(opts)` | `ribbons(opts)` | + +## Guia de seleção + +```mermaid +flowchart TD + A[Precisa começar rápido?] -->|Sim| B[Usar um preset?] + A -->|Não| C[Qual tamanho de bundle?] + B -->|Sim| D["@tsparticles/configs + @tsparticles/slim"] + B -->|Não| E["Confete? → @tsparticles/confetti"] + B -->|Não| F["Fogos? → @tsparticles/fireworks"] + B -->|Não| G["Fundo de partículas? → @tsparticles/particles"] + B -->|Não| H["Ribbons? → @tsparticles/ribbons"] + C -->|"Mínimo (apenas círculos)"| I["@tsparticles/basic"] + C -->|"Médio (formas + interações)"| J["@tsparticles/slim"] + C -->|"Máximo (todas as funcionalidades)"| K["tsparticles (loadFull)"] + C -->|"Repositório inteiro"| L["@tsparticles/all"] ``` -Precisa de links CDN e de outras variantes de gerenciador de pacotes? - -- Veja [`/guide/installation`](/pt/guide/installation). - -## Exemplos de setup - -### Bundles com engine + loader (`basic`, `slim`, `full`, `all`) - -```ts -import { tsParticles } from "@tsparticles/engine"; -import { loadSlim } from "@tsparticles/slim"; - -await loadSlim(tsParticles); - -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - number: { value: 80 }, - move: { enable: true, speed: 2 }, - }, - }, -}); +**Regras práticas:** + +1. A maioria dos projetos começa com `@tsparticles/slim`. +2. Se o tamanho do bundle é crítico e você só precisa de círculos: `@tsparticles/basic`. +3. Se você precisa de emissores, absorvedores, texto, wobble/tilt/roll: `tsparticles` com `loadFull`. +4. Para prototipagem rápida com todas as funcionalidades: `@tsparticles/all`. +5. Para efeitos específicos (confete, fogos, fundo de partículas, ribbons) com configuração mínima: bundles com API dedicada. + +## Instalação rápida + +| Bundle | Comando npm | Função de carga | URL CDN | +| ------------------------ | ------------------------------------------------- | ------------------------ | -------------------------------------------------------------- | +| `@tsparticles/basic` | `pnpm add @tsparticles/engine @tsparticles/basic` | `loadBasic(tsParticles)` | `@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| `@tsparticles/slim` | `pnpm add @tsparticles/engine @tsparticles/slim` | `loadSlim(tsParticles)` | `@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| `tsparticles` (full) | `pnpm add @tsparticles/engine tsparticles` | `loadFull(tsParticles)` | `tsparticles@4/tsparticles.bundle.min.js` | +| `@tsparticles/all` | `pnpm add @tsparticles/engine @tsparticles/all` | `loadAll(tsParticles)` | `@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| `@tsparticles/confetti` | `pnpm add @tsparticles/confetti` | `confetti(opts)` | `@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| `@tsparticles/fireworks` | `pnpm add @tsparticles/fireworks` | `fireworks(opts)` | `@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| `@tsparticles/particles` | `pnpm add @tsparticles/particles` | `particles(opts)` | `@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| `@tsparticles/ribbons` | `pnpm add @tsparticles/ribbons` | `ribbons(opts)` | `@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | + +**Nota:** para os bundles basic/slim/full/all você DEVE chamar `load*` antes de `tsParticles.load()`. Os arquivos CDN expõem a função de carga globalmente, mas NÃO a chamam automaticamente. Os bundles confetti/fireworks/particles/ribbons têm APIs autocontidas — chame `confetti()`, `fireworks()`, etc. diretamente. + +Exemplo CDN para `@tsparticles/slim`: + +```html + + + ``` -Para os outros presets, troque apenas o import/funcao do loader: +Exemplo CDN para `@tsparticles/confetti`: -- `@tsparticles/basic` -> `loadBasic` -- `tsparticles` -> `loadFull` -- `@tsparticles/all` -> `loadAll` - -### APIs focadas (`confetti`, `fireworks`, `particles`, `ribbons`) - -```ts -import { confetti } from "@tsparticles/confetti"; -import { fireworks } from "@tsparticles/fireworks"; -import { particles } from "@tsparticles/particles"; -import { ribbons } from "@tsparticles/ribbons"; - -await confetti({ count: 80, spread: 60 }); -await fireworks({ sounds: false }); -await particles({ count: 100, links: true }); -await ribbons({ count: 5, spread: 0 }); +```html + + ``` -Essas APIs sao ideais quando voce quer integrar rapido sem conectar manualmente varios plugins do engine. - -## Regras praticas de escolha - -1. Comece com `@tsparticles/slim` na maioria dos projetos. -2. Use `@tsparticles/basic` se o tamanho do bundle for a prioridade principal e os recursos forem simples. -3. Use `tsparticles` quando precisar de uma base full com muitos recursos e `loadFull`. -4. Use `@tsparticles/all` para prototipagem ou quando precisar de muitos recursos imediatamente. -5. Use `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles` ou `@tsparticles/ribbons` quando sua UI precisar de um efeito focado com setup minimo. +Consulte também o [guia de instalação](/pt/guide/installation) para detalhes sobre CDN, npm, yarn e arquivos. -## Paginas relacionadas +## Páginas relacionadas -- Bundles focados no playground: [`/playground/bundles`](/pt/playground/bundles) -- Caminho de inicio: [`/guide/getting-started`](/pt/guide/getting-started) -- Matriz de instalacao: [`/guide/installation`](/pt/guide/installation) -- Visao geral de wrappers: [`/guide/wrappers`](/pt/guide/wrappers) +- [Primeiros passos](/pt/guide/getting-started) +- [Guia de instalação](/pt/guide/installation) +- [Catálogo de presets](/pt/demos/presets) +- [Catálogo de paletas](/pt/demos/palettes) +- [Catálogo de formas](/pt/demos/shapes) diff --git a/websites/website/docs/pt/guide/color-formats.md b/websites/website/docs/pt/guide/color-formats.md index c54843da5f9..5ac10ad7fa5 100644 --- a/websites/website/docs/pt/guide/color-formats.md +++ b/websites/website/docs/pt/guide/color-formats.md @@ -1,6 +1,6 @@ # Formatos de cores -tsParticles aceita vários formatos de cores em opções como `background`, `particles.color` e configurações de plug-in. +tsParticles aceita vários formatos de cores em opções como `background`, `particles.paint` e configurações de plug-in. ## Formatos comuns diff --git a/websites/website/docs/pt/guide/getting-started.md b/websites/website/docs/pt/guide/getting-started.md index 7204c4bd361..bc09deb4f1e 100644 --- a/websites/website/docs/pt/guide/getting-started.md +++ b/websites/website/docs/pt/guide/getting-started.md @@ -1,106 +1,197 @@ # Primeiros passos -Este caminho é a configuração confiável mais rápida para `tsParticles` em 2026. +tsParticles é uma biblioteca JavaScript/TypeScript para criar animações de partículas, confetes, fogos de artifício e muito mais. Funciona em qualquer navegador moderno e está disponível tanto como pacote npm quanto via CDN com tags ` + + + + +
+ + + +``` + +> **Nota**: mesmo com bundles CDN você DEVE chamar `loadSlim(tsParticles)` (ou `loadBasic` / `loadFull` / `loadAll`) antes de `tsParticles.load()`. Os bundles CDN expõem a função de carga globalmente, mas NÃO a chamam automaticamente. + +O mesmo padrão se aplica a `@tsparticles/basic` → `loadBasic`, `tsparticles` → `loadFull`, `@tsparticles/all` → `loadAll`. + +### Caminho C — Bundles especializados com API dedicada (confete, fogos de artifício, partículas) + +Alguns bundles possuem sua própria API simplificada, sem necessidade de usar `tsParticles.load()`: + +```html + + + + + + + + + +``` + +O mesmo para `fireworks()`, `particles()`, `ribbons()`. -- `@tsparticles/slim`: a maioria dos aplicativos deve começar aqui. -- `@tsparticles/basic`: conjunto de recursos menor para configurações muito leves. -- `@tsparticles/all`: tudo incluído, mais fácil para prototipagem rápida. +## Qual bundle escolher? -Se você precisar de uma API focada em vez da configuração direta de `tsParticles`: +| Bundle | npm | Quando usar | +| ------------------------ | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `@tsparticles/basic` | `loadBasic(tsParticles)` | Mínimo: círculos, movimento, opacidade, tamanho. Sem interações. | +| `@tsparticles/slim` | `loadSlim(tsParticles)` | **Recomendado para a maioria dos projetos.** Adiciona interações (clique/passar o mouse), links entre partículas, imagens, estrelas, polígonos. | +| `tsparticles` | `loadFull(tsParticles)` | Conjunto completo oficial: emissores, absorvedores, formas de texto, roll, wobble, trail. | +| `@tsparticles/all` | `loadAll(tsParticles)` | **Tudo** no repositório: toda forma, interação, efeito, easing, caminho, exportação. Apenas para prototipagem. | +| `@tsparticles/confetti` | `confetti(options)` | Confete em uma chamada de função. API dedicada. | +| `@tsparticles/fireworks` | `fireworks(options)` | Fogos de artifício em uma chamada de função. API dedicada. | +| `@tsparticles/particles` | `particles(options)` | Fundo de partículas simplificado. API dedicada. | +| `@tsparticles/ribbons` | `ribbons(options)` | Efeito ribbon. API dedicada. | -- `@tsparticles/particles`: API de fundo de partículas simplificada -- `@tsparticles/confetti`: API de confete em uma unica chamada -- `@tsparticles/fireworks`: API de fogos de artifício em uma unica chamada +Mais detalhes: [`/pt/guide/bundles`](/pt/guide/bundles). -## 5) Use predefinições/configurações quando precisar de velocidade +## Usando presets -Se você preferir efeitos pré-construídos: +O pacote `@tsparticles/configs` contém dezenas de configurações prontas (absorvedores, bolhas, neve, estrelas, gravidade, colisões, etc.). ```bash -pnpm add @tsparticles/configs +pnpm add @tsparticles/engine @tsparticles/slim @tsparticles/configs +``` + +```ts +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import "@tsparticles/configs"; + +await loadSlim(tsParticles); + +await tsParticles.load({ + id: "tsparticles", + options: { preset: "snow" }, +}); ``` -Em seguida, carregue uma configuração por chave, como o [app `demo/vite`](https://github.com/tsparticles/tsparticles/blob/main/demo/vite/src/main.ts). +Com CDN: -Se você preferir configurações baseadas em nomes de predefinições, use o catálogo oficial de predefinições em [`/demos/presets`](/pt/demos/presets). +```html + + + + +``` -## Mapa de documentação rápida +## Referências rápidas -- Opções de raiz: [`/options/`](/pt/options/) -- Referência de wrappers: [`/guide/wrappers`](/pt/guide/wrappers) -- Catálogo de predefinições: [`/demos/presets`](/pt/demos/presets) -- Catálogo de paletas: [`/demos/palettes`](/pt/demos/palettes) -- Catalogo de formas: [`/demos/shapes`](/pt/demos/shapes) -- Migração de particles.js: [`/migrations/particles-js`](/pt/migrations/particles-js) -- Formatos de cores: [`/guide/color-formats`](/pt/guide/color-formats) -- Ciclo de vida do contêiner: [`/guide/container-lifecycle`](/pt/guide/container-lifecycle) -- Plug-ins e personalização: [`/guide/plugins-customization`](/pt/guide/plugins-customization) +- Documentação de opções: [`/pt/options/`](/pt/options/) +- Guia de bundles: [`/pt/guide/bundles`](/pt/guide/bundles) +- Catálogo de presets: [`/pt/demos/presets`](/pt/demos/presets) +- Catálogo de paletas: [`/pt/demos/palettes`](/pt/demos/palettes) +- Catálogo de formas: [`/pt/demos/shapes`](/pt/demos/shapes) +- Wrappers de frameworks: [`/pt/guide/wrappers`](/pt/guide/wrappers) +- Formatos de cor: [`/pt/guide/color-formats`](/pt/guide/color-formats) +- Ciclo de vida do contêiner: [`/pt/guide/container-lifecycle`](/pt/guide/container-lifecycle) +- Plugins e personalização: [`/pt/guide/plugins-customization`](/pt/guide/plugins-customization) ## Solução de problemas -- Tela em branco: verifique se `#tsparticles` existe antes de chamar `tsParticles.load`. -- Recurso ausente: você provavelmente precisará de outro plugin/pacote (forma, interação, atualizador). -- Erros de digitação nas opções: mantenha seus pacotes alinhados à mesma versão principal/secundária. +| Problema | Causa provável | Solução | +| ---------------------------------------------------- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| Tela em branco, sem partículas | `#tsparticles` não existe no DOM ao chamar `tsParticles.load()` | Certifique-se de que a DIV exista antes do script, ou use `DOMContentLoaded` | +| Tela em branco, sem partículas | Instalou apenas `@tsparticles/engine` | Instale também um bundle (`@tsparticles/slim`) ou plugins — o motor sozinho não tem formas para desenhar | +| Erro "loadBasic/loadSlim/loadFull is not a function" | Bundle não instalado ou import errado | `pnpm add @tsparticles/slim` e importe `{ loadSlim }` | +| Partículas não se movem | `move.enable` não definido como `true` | Adicione `move: { enable: true, speed: 2 }` | +| Funcionalidade ausente (ex.: links, colisões) | O bundle escolhido não inclui o recurso | Mude para um bundle mais completo (`@tsparticles/slim` ou `tsparticles`) ou instale o plugin específico | +| Erros de tipo TypeScript | Versões dos pacotes dessincronizadas | Mantenha o motor e o bundle na mesma versão major/minor | diff --git a/websites/website/docs/pt/guide/installation.md b/websites/website/docs/pt/guide/installation.md index 0e5df14b2ba..1a5c09f24a2 100644 --- a/websites/website/docs/pt/guide/installation.md +++ b/websites/website/docs/pt/guide/installation.md @@ -1,109 +1,146 @@ -# Instalacao - -Esta pagina replica a matriz de instalacao do README principal de `tsParticles`. - -Referencia oficial: +# Instalação ## Escolha seu caminho -- **Padrao rapido**: `@tsparticles/engine` + `@tsparticles/slim` -- **Runtime personalizado mais leve**: `@tsparticles/engine` + apenas plugins necessarios -- **APIs focadas**: `@tsparticles/particles`, `@tsparticles/confetti`, `@tsparticles/fireworks` ou `@tsparticles/ribbons` -- **Todos os recursos incluidos**: `@tsparticles/all` - -## Hospedagem / CDN - -Use um destes provedores (ou hospede voce mesmo os arquivos gerados). +| Cenário | Comando | +| ------------------------------------ | ------------------------------------------------- | +| Início rápido (recomendado) | `pnpm add @tsparticles/engine @tsparticles/slim` | +| Configuração mínima | `pnpm add @tsparticles/engine @tsparticles/basic` | +| Conjunto completo de funcionalidades | `pnpm add @tsparticles/engine tsparticles` | +| Tudo no repositório | `pnpm add @tsparticles/engine @tsparticles/all` | +| Apenas confete | `pnpm add @tsparticles/confetti` | +| Apenas fogos de artifício | `pnpm add @tsparticles/fireworks` | +| Fundo de partículas | `pnpm add @tsparticles/particles` | +| Efeito ribbon | `pnpm add @tsparticles/ribbons` | -### jsDelivr +> **Importante**: `@tsparticles/engine` sozinho não desenha nada. Você deve sempre adicionar um bundle (para carregar formas e animações) ou plugins individuais. Consulte o [guia de bundles](/pt/guide/bundles). -- -- -- -- -- -- -- -- +## npm -### cdnjs +```bash +# engine + slim (recomendado para a maioria dos projetos) +npm install @tsparticles/engine @tsparticles/slim -- +# engine + basic (mínimo) +npm install @tsparticles/engine @tsparticles/basic -### unpkg +# engine + full (tsparticles) +npm install @tsparticles/engine tsparticles -- -- -- -- -- -- -- -- +# engine + all +npm install @tsparticles/engine @tsparticles/all -## Instalacao via package manager +# Bundles com API dedicada (sem engine explícito) +npm install @tsparticles/confetti +npm install @tsparticles/fireworks +npm install @tsparticles/particles +npm install @tsparticles/ribbons +``` -### npm +## yarn ```bash -npm install @tsparticles/engine +yarn add @tsparticles/engine @tsparticles/slim +# ... mesmo padrão para outros bundles ``` -### yarn +## pnpm ```bash -yarn add @tsparticles/engine +pnpm add @tsparticles/engine @tsparticles/slim +# ... mesmo padrão para outros bundles ``` -### pnpm +## CDN (script tags) -```bash -pnpm add @tsparticles/engine -``` +Todos os pacotes estão disponíveis no jsDelivr, unpkg e cdnjs. -## Import e require +### jsDelivr -```ts -const tsParticles = require("@tsparticles/engine"); +| Bundle | URL | +| ---------------------------- | ------------------------------------------------------------------------------------------- | +| Engine | `https://cdn.jsdelivr.net/npm/@tsparticles/engine@4/tsparticles.engine.min.js` | +| Basic | `https://cdn.jsdelivr.net/npm/@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| Slim | `https://cdn.jsdelivr.net/npm/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| Full (`tsparticles`) | `https://cdn.jsdelivr.net/npm/tsparticles@4/tsparticles.bundle.min.js` | +| All | `https://cdn.jsdelivr.net/npm/@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| Confetti | `https://cdn.jsdelivr.net/npm/@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| Fireworks | `https://cdn.jsdelivr.net/npm/@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| Particles | `https://cdn.jsdelivr.net/npm/@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| Ribbons | `https://cdn.jsdelivr.net/npm/@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | +| Compatibilidade particles.js | `https://cdn.jsdelivr.net/npm/@tsparticles/pjs@4/tsparticles.pjs.min.js` | -// or +### unpkg -import { tsParticles } from "@tsparticles/engine"; -``` +Mesma estrutura: `https://unpkg.com/{nome-do-pacote}@{versão}/{arquivo}` + +Exemplo: +`https://unpkg.com/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` + +### cdnjs -## Configuracao minima de runtime (`@tsparticles/slim`) +`https://cdnjs.com/libraries/tsparticles` + +## Exemplos de importação + +### Com bundler (importação ES module) ```ts +// Engine + loader do bundle import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; await loadSlim(tsParticles); +await tsParticles.load({ id: "tsparticles", options: { ... } }); +``` -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - move: { - enable: true, - }, - number: { - value: 60, - }, - }, - }, -}); +### Com CommonJS (require) + +```ts +const { tsParticles } = require("@tsparticles/engine"); +const { loadSlim } = require("@tsparticles/slim"); + +(async () => { + await loadSlim(tsParticles); + await tsParticles.load({ id: "tsparticles", options: { ... } }); +})(); ``` -## Paginas relacionadas +### Com CDN (script tag) + +```html + + + + + + +``` -- [`/guide/getting-started`](/pt/guide/getting-started) -- [`/guide/wrappers`](/pt/guide/wrappers) -- [`/demos/presets`](/pt/demos/presets) -- [`/migrations/particles-js`](/pt/migrations/particles-js) +Com bundles de API dedicada: -## Compatibilidade legada +```html + + +``` -Se voce estiver migrando integracoes antigas de particles.js, use o pacote de compatibilidade: +## Páginas relacionadas -- npm: -- jsDelivr: +- [Primeiros passos](/pt/guide/getting-started) +- [Guia de bundles](/pt/guide/bundles) +- [Wrappers de frameworks](/pt/guide/wrappers) diff --git a/websites/website/docs/pt/guides/angular.md b/websites/website/docs/pt/guides/angular.md new file mode 100644 index 00000000000..f5f386cc676 --- /dev/null +++ b/websites/website/docs/pt/guides/angular.md @@ -0,0 +1,631 @@ +--- +title: Integração Angular +description: Guia passo a passo para integrar tsParticles em aplicações Angular usando @tsparticles/angular. +--- + +# Integração Angular + +O pacote `@tsparticles/angular` fornece componentes, módulos e serviços Angular para tsParticles. Este guia aborda a abordagem tradicional com `NgModule` bem como componentes standalone no Angular 17+. + +--- + +## Instalação + +```bash +npm install @tsparticles/angular @tsparticles/engine +``` + +Para o conjunto completo de funcionalidades, instale o pacote completo: + +```bash +npm install tsparticles +``` + +Pacotes de presets opcionais: + +```bash +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +``` + +--- + +## Uso Básico (NgModule) + +### 1. Importar o Módulo + +```typescript +import { NgModule } from "@angular/core"; +import { BrowserModule } from "@angular/platform-browser"; +import { NgParticlesModule } from "@tsparticles/angular"; +import { AppComponent } from "./app.component"; + +@NgModule({ + declarations: [AppComponent], + imports: [BrowserModule, NgParticlesModule], + bootstrap: [AppComponent], +}) +export class AppModule {} +``` + +### 2. Inicializar o Motor + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d47a1", + }, + fpsLimit: 120, + particles: { + number: { + value: 80, + }, + color: { + value: "#ffffff", + }, + shape: { + type: "circle", + }, + opacity: { + value: 0.5, + }, + size: { + value: { min: 1, max: 5 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Container de partículas carregado", container); + } +} +``` + +### 3. Template + +```html + +``` + +--- + +## Detalhes da Inicialização do Motor + +O método `NgParticlesService.init()` deve ser chamado exatamente uma vez, normalmente em `AppComponent.ngOnInit()`. Ele recebe um callback onde você carrega os plugins/presets que sua aplicação precisa. + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesService } from "@tsparticles/angular"; +import type { Engine } from "@tsparticles/engine"; + +@Component({ ... }) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + // Carregue apenas o necessário para bundles menores + await loadBasic(engine); // formas básicas + movimento + await loadEmittersPlugin(engine); // formas de emissores + }); + } +} +``` + +Funções de carregamento disponíveis no `tsparticles`: + +| Função | Descrição | +| ------------------- | ----------------------------------------------------- | +| `loadFull(engine)` | Todas as funcionalidades (maior bundle) | +| `loadBasic(engine)` | Formas principais (círculo, quadrado, polígono, etc.) | +| `loadSlim(engine)` | Maioria das funcionalidades menos plugins raros | +| `loadAll(engine)` | Alias obsoleto para `loadFull` | + +--- + +## Efeito Confete + +```bash +npm install @tsparticles/preset-confetti +``` + +```typescript +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// No callback do NgParticlesService.init: +await loadConfettiPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "confetti", + background: { + color: "transparent", + }, +}; +``` + +Ou use o componente conveniente ``: + +```typescript +// app.module.ts +import { NgParticlesModule } from "@tsparticles/angular"; + +@NgModule({ + imports: [NgParticlesModule], +}) +export class AppModule {} +``` + +```html + +``` + +--- + +## Efeito Fogos de Artifício + +```bash +npm install @tsparticles/preset-fireworks +``` + +```typescript +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; + +// No callback do NgParticlesService.init: +await loadFireworksPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "fireworks", + background: { + color: "#000000", + }, +}; +``` + +Ou use o componente ``: + +```html + +``` + +> Evite iniciar fogos de artifício automaticamente; vincule-os a uma ação do usuário (clique, scroll) para evitar uso indesejado de recursos. + +--- + +## Configuração Personalizada de Partículas + +Configuração personalizada completa com interatividade: + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-particles", + templateUrl: "./particles.component.html", +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d0d0d", + }, + fpsLimit: 60, + particles: { + number: { + value: 100, + density: { + enable: true, + }, + }, + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + shape: { + type: ["circle", "square", "triangle"], + }, + opacity: { + value: 0.8, + random: true, + anim: { + enable: true, + speed: 1, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + random: true, + anim: { + enable: true, + speed: 4, + size_min: 1, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.3, + width: 1, + triangles: { + enable: true, + color: "#ffffff", + opacity: 0.05, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { + enable: true, + rotateX: 600, + rotateY: 600, + }, + }, + life: { + duration: { + value: 5, + random: true, + }, + count: 0, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: { + enable: true, + }, + }, + modes: { + grab: { + distance: 200, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + detectRetina: true, + }; + + particlesLoaded(container: Container): void { + console.log("Container carregado", container); + } +} +``` + +```html + +``` + +--- + +## Eventos + +O componente `ngx-particles` emite o evento `particlesLoaded`: + +```typescript +import type { Container } from "@tsparticles/engine"; + +// Método do componente +onParticlesLoaded(container: Container): void { + // Acesse a API do container + container.pause(); + container.play(); + container.destroy(); + container.exportImage().then((blob) => { /* ... */ }); +} +``` + +```html + +``` + +A referência do container oferece controle programático completo: pausar, retomar, destruir, exportar e mais. + +--- + +## Sintaxe de Template e Renderização Condicional + +Use diretivas estruturais do Angular para alternar o componente: + +```html + + + +``` + +```typescript +export class AppComponent { + showParticles = true; + // ... +} +``` + +Quando `*ngIf` é avaliado como `false`, o componente é destruído (incluindo o canvas e todas as instâncias de partículas). Recriá-lo reinicializa tudo do zero. + +--- + +## Componentes Standalone (Angular 17+) + +No Angular 17+, você pode importar `NgParticlesModule` diretamente em um componente standalone: + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesModule, NgParticlesService } from "@tsparticles/angular"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +@Component({ + selector: "app-particles", + standalone: true, + imports: [NgParticlesModule], + template: ` + + `, +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 50 }, + color: { value: "#fff" }, + shape: { type: "circle" }, + move: { enable: true, speed: 2 }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Carregado", container); + } +} +``` + +Nenhum wrapper `NgModule` necessário — basta importar `NgParticlesModule` no array `imports` do componente. + +--- + +## Exemplo de Componente Completo + +### app.component.ts + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + title = "tsParticles Angular Demo"; + + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadSlim(engine); + }); + } + + particlesOptions: ISourceOptions = { + autoPlay: true, + background: { + color: "#1e1e2e", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMask: { + cover: { + color: "#1e1e2e", + }, + enable: false, + }, + fullScreen: { + enable: true, + zIndex: -1, + }, + detectRetina: true, + fpsLimit: 60, + particles: { + color: { + value: "#cdd6f4", + }, + links: { + color: "#cdd6f4", + distance: 150, + enable: true, + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1, + }, + number: { + value: 60, + }, + opacity: { + value: 0.6, + }, + size: { + value: { min: 1, max: 3 }, + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Partículas carregadas", container); + } +} +``` + +### app.component.html + +```html +
+ + +
+

{{ title }}

+

As partículas estão sendo executadas no fundo.

+
+
+``` + +### app.component.css + +```css +:host { + display: block; + width: 100%; + height: 100%; +} +``` + +--- + +## Referência da API + +| Componente | Seletor | Descrição | +| ---------- | --------------- | -------------------------------------------- | +| Particles | `ngx-particles` | Componente completo do sistema de partículas | +| Confetti | `ngx-confetti` | Efeito de confete pré-configurado | +| Fireworks | `ngx-fireworks` | Efeito de fogos de artifício pré-configurado | + +### Inputs do `ngx-particles` + +| Input | Tipo | Padrão | Descrição | +| --------- | ---------------- | --------------- | ------------------------------- | +| `id` | `string` | `"tsparticles"` | ID do elemento canvas | +| `options` | `ISourceOptions` | `{}` | Configuração das partículas | +| `url` | `string` | — | URL de configuração JSON remota | + +### Outputs do `ngx-particles` + +| Output | Payload | Descrição | +| ----------------- | ----------- | ----------------------------------------- | +| `particlesLoaded` | `Container` | Emitido quando o container é inicializado | + +--- + +## Solução de Problemas + +- **Canvas em branco / invisível** — Certifique-se de que o elemento pai tenha uma altura definida (ex.: `height: 100vh`). O canvas assume as dimensões do container. +- **`NgParticlesService.init()` chamado várias vezes** — Chame-o apenas uma vez, tipicamente em `AppComponent.ngOnInit()`. Chamadas subsequentes são seguras mas redundantes. +- **Módulo não encontrado** — Verifique se `@tsparticles/angular` está listado nas dependências do `package.json` e que você importou `NgParticlesModule`. +- **`NullInjectorError: No provider for NgParticlesService`** — Você deve importar `NgParticlesModule` (ou re-exportá-lo) no módulo onde você fornece o componente. diff --git a/websites/website/docs/pt/guides/astro.md b/websites/website/docs/pt/guides/astro.md new file mode 100644 index 00000000000..bd86fe2f931 --- /dev/null +++ b/websites/website/docs/pt/guides/astro.md @@ -0,0 +1,384 @@ +# Integração Astro + +Use tsParticles no seu site Astro com o pacote de integração oficial `@tsparticles/astro`. + +## Instalação + +Instale a integração Astro e o núcleo tsParticles através do seu gerenciador de pacotes: + +```bash +npm install @tsparticles/astro tsparticles +``` + +```bash +pnpm add @tsparticles/astro tsparticles +``` + +```bash +yarn add @tsparticles/astro tsparticles +``` + +## Inicialização do Motor + +tsParticles usa uma arquitetura modular. Antes de renderizar partículas, você deve inicializar o motor com as funcionalidades necessárias. Crie um script cliente (ex.: `src/scripts/particles-init.ts`) ou use um ` +``` + +> A prop `id` é passada para o `
` subjacente do container do canvas. Use-a para estilização ou acesso imperativo via `document.getElementById()`. + +## Suporte a TypeScript + +A integração inclui declarações TypeScript completas. Use `ISourceOptions` de `@tsparticles/engine` para tipar sua configuração: + +```typescript +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { + value: 50, + density: { enable: true }, + }, + opacity: { value: 0.5 }, + shape: { type: "circle" }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + repulse: { distance: 200 }, + }, + }, +}; +``` + +## Configuração Personalizada + +Abaixo está uma configuração mais elaborada que você pode usar em qualquer página Astro: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + autoPlay: true, + background: { + color: "#0d47a1", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMode: { + enable: true, + zIndex: -1, + }, + fpsLimit: 120, + particles: { + color: { + value: "#ffffff", + animation: { + enable: true, + speed: 20, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + triangles: { + enable: true, + opacity: 0.1, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "out", + attract: { enable: false }, + }, + number: { + value: 80, + density: { + enable: true, + }, + }, + opacity: { + value: 0.5, + animation: { + enable: true, + speed: 1, + sync: false, + }, + }, + shape: { + type: "circle", + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 3, + sync: false, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: true, + }, + modes: { + grab: { + distance: 200, + links: { opacity: 0.5 }, + }, + push: { quantity: 4 }, + }, + }, + detectRetina: true, +}; +--- + + + + +``` + +## Usando Presets + +Em vez de construir uma configuração manualmente, carregue um preset durante a inicialização do motor e referencie-o nas opções: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + preset: "stars", + background: { color: "#000000" }, +}; +--- + + + + +``` + +## Integração com Outros Frameworks + +Como o Astro suporta frameworks de UI como React, Vue, Svelte e Solid, você pode usar o componente tsParticles específico do framework dentro de arquivos `.astro`: + +### React no Astro + +```astro +--- +import Particles from "@tsparticles/react"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +### Vue no Astro + +```astro +--- +import Particles from "@tsparticles/vue3"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +> A diretiva `client:load` diz ao Astro para hidratar o componente imediatamente ao carregar a página. Use `client:visible` para carregamento adiado. + +## Exemplo de Página Completa + +Uma página Astro completa com partículas servindo como fundo animado: + +```astro +--- +import Layout from "../layouts/Layout.astro"; +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + number: { value: 100 }, + color: { value: "#ffffff" }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + size: { + value: { min: 1, max: 4 }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, +}; +--- + + +
+

Bem-vindo

+

Esta página tem um fundo de partículas desenvolvido com tsParticles.

+
+ +
+ + + + +``` + +## Props do Componente + +| Prop | Tipo | Padrão | Descrição | +| -------------------- | ---------------- | ------------------------- | ---------------------------------------------- | +| `id` | `string` | `"tsparticles"` | ID do elemento DOM para o container | +| `options` | `ISourceOptions` | `{}` | Objeto de configuração completo do tsParticles | +| `url` | `string` | — | Carregar configuração de uma URL JSON remota | +| `particlesClassName` | `string` | `"tsparticles-canvas-el"` | Classe CSS para o elemento canvas | +| `container` | `object` | — | Instância `Container` pré-existente (avançado) | diff --git a/websites/website/docs/pt/guides/ember.md b/websites/website/docs/pt/guides/ember.md new file mode 100644 index 00000000000..30d56c80758 --- /dev/null +++ b/websites/website/docs/pt/guides/ember.md @@ -0,0 +1,346 @@ +--- +title: Guia Ember +description: Guia completo para integrar tsParticles com aplicações Ember.js. +--- + +# Guia Ember + +## Índice + +1. [Instalação](#instalação) +2. [Inicialização do Motor](#inicialização-do-motor) +3. [Uso Básico](#uso-básico) +4. [Configuração Personalizada](#configuração-personalizada) +5. [Manipulação de Eventos](#manipulação-de-eventos) +6. [Renderização Condicional](#renderização-condicional) +7. [Exemplo TypeScript](#exemplo-typescript) + +--- + +## Instalação + +Instale o addon Ember e o motor tsParticles via ember-cli: + +```bash +ember install @tsparticles/ember +``` + +Isso instalará o addon e sua dependência `tsparticles`. Você pode opcionalmente adicionar pacotes de preset: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Inicialização do Motor + +O addon exporta um utilitário `initParticlesEngine` que você chama uma vez no nível da aplicação. Ele recebe um callback assíncrono onde você carrega as funcionalidades, presets ou formas que sua aplicação precisa. + +```typescript +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadFull } from "tsparticles"; + +// Chame isso durante a inicialização da aplicação +if (typeof window !== "undefined") { + void initParticlesEngine(async (engine) => { + await loadFull(engine); + }); +} +``` + +Locais típicos para esta chamada são o hook `beforeModel` da rota da aplicação, o construtor de um controller da aplicação, ou um inicializador de instância. O singleton do motor é inicializado uma vez e compartilhado entre todos os componentes `` na sua aplicação. + +--- + +## Uso Básico + +Após inicializar o motor, use o componente `` em qualquer template. Passe sua configuração de partículas através do argumento `@options`. + +```hbs +{{! app/templates/application.hbs }} + + +``` + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, + }; +} +``` + +--- + +## Configuração Personalizada + +Construa uma configuração mais rica com interatividade, múltiplas formas e densidade responsiva. + +```typescript +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class IndexController extends Controller { + options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, + }; +} +``` + +```hbs + +``` + +--- + +## Manipulação de Eventos + +O componente `` dispara uma ação `@particlesLoaded` quando o container terminou de inicializar e o primeiro frame foi renderizado. Use isso para acessar a instância `Container` para controle programático. + +```typescript +import Controller from "@ember/controller"; +import { action } from "@ember/object"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + /* ... */ + }; + + @action + loadedCallback(container: Container) { + console.log("Partículas carregadas", container.id); + + // Exemplo de controle programático: + setTimeout(() => { + container.pause(); + console.log("Partículas pausadas após 5 segundos"); + }, 5000); + } +} +``` + +```hbs + +``` + +Você também pode usar o padrão de callback inline com um helper de template se preferir não definir uma ação separada. + +--- + +## Renderização Condicional + +Use o helper `{{if}}` do Ember junto com uma propriedade `@tracked` para controlar quando o componente `` renderiza. Isso é útil quando a inicialização do motor é assíncrona e você quer evitar renderizar o componente antes que o motor esteja pronto. + +```typescript +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked engineReady = false; + + options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { enable: true, speed: 1, outModes: { default: "bounce" } }, + }, + background: { color: "#1a1a2e" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } +} +``` + +```hbs +{{#if this.engineReady}} + +{{else}} +

Carregando partículas...

+{{/if}} +``` + +O decorador `@tracked` garante que o template re-renderize automaticamente assim que a promise resolver. + +--- + +## Exemplo TypeScript + +Abaixo está um controller de aplicação Ember completo e tipado demonstrando o padrão de integração completo com preset slim, interatividade e gerenciamento de ciclo de vida. + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked private engineReady = false; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } + + @action + private handleParticlesLoaded(container: Container): void { + this.container = container; + console.log("Partículas carregadas no container:", container.id); + } +} +``` + +```hbs +{{! app/templates/application.hbs }} + +{{#if this.engineReady}} +
+

tsParticles + Ember

+ +
+{{else}} +
+

Inicializando motor de partículas...

+
+{{/if}} +``` + +--- + +Você tem agora tudo que precisa para integrar tsParticles em uma aplicação Ember.js. Cada exemplo é autocontido e pronto para ser copiado para o seu projeto. diff --git a/websites/website/docs/pt/guides/index.md b/websites/website/docs/pt/guides/index.md new file mode 100644 index 00000000000..04c3220c9c0 --- /dev/null +++ b/websites/website/docs/pt/guides/index.md @@ -0,0 +1,58 @@ +--- +title: Guias Passo a Passo +description: Explore guias específicos para frameworks para integrar tsParticles no seu projeto. +--- + +# Guias Passo a Passo + +Bem-vindo à seção de guias do tsParticles. Quer você esteja construindo um site estático Vanilla JS, um aplicativo de página única em React ou Vue, ou uma aplicação full-stack com Next.js ou Nuxt, estes tutoriais passo a passo guiarão você pela instalação, uso básico, configurações avançadas e efeitos interativos. + +Cada guia é autocontido e inclui exemplos de código copiáveis para que você possa começar rapidamente. + +## Guias Disponíveis + +| Framework / Wrapper | Pacote | Descrição | +| --------------------------------- | ------------------------------------------ | ---------------------------------------------------- | +| [Vanilla JS](./vanilla) | `tsparticles` (CDN ou npm) | Integração DOM direta com `tsParticles.load()` | +| [React](./react) | `@tsparticles/react` | Wrapper React oficial com hooks e API de componentes | +| [Vue 3](./vue3) | `@tsparticles/vue3` | Plugin Vue 3 oficial com composables | +| [Angular](./angular) | `@tsparticles/angular` | Componente e módulo Angular oficial | +| [Svelte](./svelte) | `@tsparticles/svelte` | Componente Svelte oficial | +| [Next.js](./nextjs) | `@tsparticles/react` (com Next.js) | Renderização no servidor e importações dinâmicas | +| [Nuxt](./nuxt) | `@tsparticles/vue3` (com Nuxt) | Integração SSR-safe como plugin Nuxt | +| [Solid](./solid) | `@tsparticles/solid` | Wrapper SolidJS oficial | +| [Preact](./preact) | `@tsparticles/preact` | Componente compatível com Preact | +| [Lit](./lit) | `@tsparticles/lit` | Wrapper de web component Lit | +| [Qwik](./qwik) | `@tsparticles/qwik` | Integração otimizada para Qwik | +| [jQuery](./jquery) | `@tsparticles/jquery` | Plugin jQuery para projetos legados | +| [Astro](./astro) | `@tsparticles/react` (ou qualquer wrapper) | Arquitetura de ilhas com diretivas cliente | +| [Web Components](./webcomponents) | `@tsparticles/webcomponents` | Integração com API de Custom Elements | +| [Stencil](./stencil) | `@tsparticles/stencil` | Wrapper de componente Stencil | +| [Ember](./ember) | `@tsparticles/ember` | Integração addon Ember | +| [Riot](./riot) | `@tsparticles/riot` | Wrapper Riot.js | +| [Inferno](./inferno) | `@tsparticles/inferno` | Componente compatível com Inferno | +| [WordPress](./wordpress) | Plugin + `tsparticles` | Integração com editor de blocos / shortcode | + +## Escolha Seu Guia + +- [Vanilla JS (JavaScript puro)](./vanilla) +- [React](./react) +- [Vue 3](./vue3) +- [Angular](./angular) +- [Svelte](./svelte) +- [Next.js](./nextjs) +- [Nuxt](./nuxt) +- [Solid](./solid) +- [Preact](./preact) +- [Lit](./lit) +- [Qwik](./qwik) +- [jQuery](./jquery) +- [Astro](./astro) +- [Web Components](./webcomponents) +- [Stencil](./stencil) +- [Ember](./ember) +- [Riot](./riot) +- [Inferno](./inferno) +- [WordPress](./wordpress) + +Boas construções! diff --git a/websites/website/docs/pt/guides/inferno.md b/websites/website/docs/pt/guides/inferno.md new file mode 100644 index 00000000000..6e633400a49 --- /dev/null +++ b/websites/website/docs/pt/guides/inferno.md @@ -0,0 +1,373 @@ +--- +title: Guia Inferno +description: Guia completo para integrar tsParticles com aplicações Inferno. +--- + +# Guia Inferno + +## Índice + +1. [Instalação](#instalação) +2. [Uso Básico](#uso-básico) +3. [Inicialização do Motor](#inicialização-do-motor) +4. [Configuração Personalizada](#configuração-personalizada) +5. [Uso de Presets](#uso-de-presets) +6. [Padrão de Componente](#padrão-de-componente) +7. [Exemplo TypeScript](#exemplo-typescript) + +--- + +## Instalação + +Instale o wrapper Inferno e o motor tsParticles via npm: + +```bash +npm install @tsparticles/inferno tsparticles +``` + +Opcionalmente instale o preset slim para um bundle menor: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Uso Básico + +O pacote `@tsparticles/inferno` exporta dois itens: `ParticlesProvider` e `Particles`. Envolva seus componentes de partículas com `ParticlesProvider`, que aceita um callback `init` para configuração do motor, e então use `` para renderizar o canvas de partículas. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import { loadSlim } from "@tsparticles/slim"; + +const options = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +function App() { + return ( + { + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +`ParticlesProvider` deve ser um ancestral de cada componente ``. Ele inicializa o motor uma vez e o fornece via contexto para todos os filhos. + +--- + +## Inicialização do Motor + +O `ParticlesProvider` aceita uma prop `init` que recebe a instância do motor. É aqui que você carrega as funcionalidades, formas, presets ou atualizadores que sua aplicação precisa. + +```tsx +// Leve — partículas circulares, movimento básico, links + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); +}}> + +// Conjunto completo de funcionalidades — todas as formas, interações, efeitos + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); +}}> + +// Preset específico — confete, fogos de artifício, neve, estrelas + { + const { loadConfettiPreset } = await import("@tsparticles/preset-confetti"); + await loadConfettiPreset(engine); +}}> +``` + +Usar `import()` dinâmico dentro do callback permite divisão de código: os módulos de preset ou funcionalidades são carregados apenas quando o componente de partículas monta. + +--- + +## Configuração Personalizada + +Abaixo está uma configuração completa com interatividade, múltiplos tipos de forma e um fundo gradiente escuro. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, +}; + +function App() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +--- + +## Uso de Presets + +O pacote `@tsparticles/configs` oferece configurações pré-construídas que você pode passar diretamente para a prop `options`. Combine-as com o carregador de preset correspondente no callback init do `ParticlesProvider`. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import configs from "@tsparticles/configs"; + +function App() { + return ( + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +Você pode trocar `configs.confetti` por qualquer preset disponível: `configs.basic`, `configs.fireworks`, `configs.snow`, `configs.stars`, etc. + +--- + +## Padrão de Componente + +Para aplicações maiores, estruture sua lógica de partículas em um componente dedicado com um callback `particlesLoaded` para acessar a instância `Container`. + +```tsx +import { render, Component } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +class ParticlesBackground extends Component { + private container?: Container; + + handleParticlesLoaded(container?: Container) { + this.container = container; + console.log("Partículas carregadas:", container?.id); + } + + render() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); + } +} + +function App() { + return ( +
+

tsParticles + Inferno

+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +## Exemplo TypeScript + +Aqui está uma aplicação Inferno completa e tipada com uma configuração de partículas responsiva e fundo de tela cheia. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const particlesOptions: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +function handleInit(engine: Engine): Promise { + return import("@tsparticles/slim").then(({ loadSlim }) => loadSlim(engine)); +} + +function handleParticlesLoaded(container?: Container): void { + console.log("Container tsParticles pronto:", container?.id); +} + +function App() { + return ( + +
+

tsParticles + Inferno

+

Integração TypeScript completa

+
+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +Você tem agora tudo que precisa para integrar tsParticles em uma aplicação Inferno. Cada exemplo é autocontido e pronto para ser copiado para o seu projeto. diff --git a/websites/website/docs/pt/guides/jquery.md b/websites/website/docs/pt/guides/jquery.md new file mode 100644 index 00000000000..bb85e64ec7e --- /dev/null +++ b/websites/website/docs/pt/guides/jquery.md @@ -0,0 +1,274 @@ +# Integração jQuery + +Integre tsParticles nos seus projetos baseados em jQuery com o wrapper oficial do plugin jQuery. + +## Instalação + +### Via CDN + +Inclua jQuery, tsParticles e o plugin jQuery através de tags script: + +```html + + + +``` + +--- + +### Via npm + Build + +Instale os pacotes necessários: + +```bash +npm install jquery @tsparticles/jquery tsparticles +``` + +Importe para o seu projeto: + +```javascript +import $ from "jquery"; +import "@tsparticles/jquery"; +``` + +## Inicialização do Motor + +Antes que as partículas possam ser renderizadas, o motor tsParticles deve ser inicializado com as funcionalidades necessárias. Isso é feito via `$.particles.init`: + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); +})(); +``` + +> **Por que isso é necessário?** tsParticles usa uma arquitetura modular. `loadFull` registra todas as formas, interações e atualizadores integrados. Você pode importar bundles menores (ex.: `tsparticles-slim`) para reduzir o tamanho do bundle. + +## Uso Básico + +Uma vez que o motor está inicializado e o DOM está pronto, selecione um elemento container e chame `.particles().load()`: + +```javascript +$(document).ready(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); + + $("#tsparticles") + .particles() + .load({ + background: { + color: "#0d47a1", + }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + }, + }); +}); +``` + +O elemento container deve existir no DOM: + +```html +
+``` + +## Configuração Personalizada + +O método `.load()` aceita o objeto `ISourceOptions` completo. Aqui está um exemplo abrangente: + +```javascript +$("#tsparticles") + .particles() + .load({ + background: { + color: "#000000", + }, + fpsLimit: 120, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + direction: "none", + enable: true, + outModes: "bounce", + speed: 4, + }, + number: { + density: { + enable: true, + }, + value: 60, + }, + opacity: { + value: 0.6, + }, + shape: { + type: ["circle", "square", "triangle"], + }, + size: { + value: { min: 2, max: 8 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + }, + interactivity: { + events: { + onClick: { + enable: true, + mode: "push", + }, + onHover: { + enable: true, + mode: "repulse", + }, + }, + modes: { + push: { + quantity: 4, + }, + repulse: { + distance: 200, + }, + }, + }, + }); +``` + +## Carregamento de Presets + +Se você instalou um pacote de preset (ex.: `tsparticles-preset-stars`), carregue-o durante a inicialização do motor e referencie-o na configuração: + +```bash +npm install tsparticles-preset-stars +``` + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadStarsPreset } = await import("tsparticles-preset-stars"); + await loadStarsPreset(engine); + }); + + $("#tsparticles") + .particles() + .load({ + preset: "stars", + background: { color: "#0d47a1" }, + }); +})(); +``` + +## Manipulação de Eventos e Controle do Container + +`.particles()` retorna uma instância do plugin jQuery. Para acessar o `Container` subjacente do tsParticles e chamar métodos como `play()`, `pause()` ou `destroy()`: + +```javascript +const $container = $("#tsparticles"); + +// Carregar partículas +$container.particles().load({ + /* opções */ +}); + +// Tocar/pausar após alguns segundos +setTimeout(() => { + const container = $container.particles().getContainer(); + container?.pause(); +}, 5000); +``` + +## Exemplo Completo + +Abaixo está uma página HTML completa e autocontida que carrega tsParticles via CDN e renderiza uma cena de partículas com efeitos interativos: + +```html + + + + + + tsParticles + jQuery + + + +
+ + + + + + + +``` + +## Referência da API + +| Método | Descrição | +| ---------------------------------- | ---------------------------------------------------------- | +| `$.particles.init(fn)` | Inicializar o motor com um callback de carregamento | +| `$(el).particles()` | Criar uma instância do plugin de partículas no elemento | +| `$(el).particles().load(opts)` | Carregar e iniciar a configuração de partículas | +| `$(el).particles().destroy()` | Destruir a instância de partículas e limpar | +| `$(el).particles().getContainer()` | Retornar o `Container` subjacente para controle imperativo | diff --git a/websites/website/docs/pt/guides/lit.md b/websites/website/docs/pt/guides/lit.md new file mode 100644 index 00000000000..4462b717fe9 --- /dev/null +++ b/websites/website/docs/pt/guides/lit.md @@ -0,0 +1,301 @@ +--- +title: Lit +description: Integre tsParticles com Lit usando o wrapper oficial de web component @tsparticles/lit. +--- + +# Integração Lit + +O pacote `@tsparticles/lit` fornece um elemento personalizado `` construído com Lit, permitindo usar tsParticles declarativamente em qualquer projeto Lit ou página HTML pura. + +## Instalação + +```bash +npm install @tsparticles/lit tsparticles +``` + +O pacote é totalmente tipado e inclui os padrões de controller reativo do Lit para atualizar reativamente as opções de partículas. + +## Inicialização do Motor + +Chame `initParticlesEngine` antes de registrar o componente `` ou importá-lo na sua aplicação. Isso deve acontecer exatamente uma vez. + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadFull } from "tsparticles"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +Para tamanhos de bundle otimizados, importe apenas as funcionalidades que seu projeto precisa: + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadBasic } from "@tsparticles/basic"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +void initParticlesEngine(async (engine) => { + await loadBasic(engine); + await loadConfettiPreset(engine); +}); +``` + +## Uso Básico + +Após o motor ser inicializado, use o elemento `` em qualquer template Lit ou arquivo HTML: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private options = { + background: { + color: "#0d1117", + }, + particles: { + number: { value: 60 }, + color: { value: "#58a6ff" }, + links: { + enable: true, + color: "#58a6ff", + }, + move: { enable: true, speed: 2 }, + }, + }; + + render() { + return html` `; + } +} +``` + +A sintaxe `.options` (com ponto inicial) é a vinculação de propriedade do Lit, garantindo que o objeto seja passado por referência em vez de serializado como atributo. + +## Uso em HTML Puro + +Uma vez que `@tsparticles/lit` é empacotado ou carregado, o elemento funciona também em HTML puro: + +```html + + + + + + + + + +``` + +Você pode passar um objeto de opções mínimo como um atributo JSON: + +```html + +``` + +## Configuração Personalizada + +Passe uma configuração completa do tsParticles como propriedade Lit: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-particles") +class MyParticles extends LitElement { + @property({ type: Object }) + options: ISourceOptions = { + background: { + color: "#0d1117", + }, + fpsLimit: 120, + fullScreen: { + enable: true, + zIndex: -1, + }, + particles: { + color: { + value: ["#ff5733", "#33ff57", "#3357ff"], + }, + links: { + color: "#ffffff", + enable: true, + opacity: 0.3, + distance: 150, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + }, + number: { + value: 100, + density: { + enable: true, + }, + }, + opacity: { + value: 0.6, + animation: { + enable: true, + speed: 0.5, + minimumValue: 0.1, + }, + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 2, + minimumValue: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + }, + modes: { + grab: { + distance: 180, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + }; + + render() { + return html` `; + } +} +``` + +## Manipulação de Eventos + +Escute o evento personalizado `particles-loaded` disparado pelo elemento ``: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import type { Container } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private handleParticlesLoaded(e: CustomEvent) { + const container = e.detail; + console.log("Partículas carregadas:", container); + container?.refresh(); + } + + render() { + return html` `; + } +} +``` + +## Exemplo TypeScript + +Um elemento Lit totalmente tipado com `initParticlesEngine`, opções reativas e manipulação de eventos: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import { initParticlesEngine } from "@tsparticles/lit"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import "@tsparticles/lit"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +@customElement("particles-background") +class ParticlesBackground extends LitElement { + @property({ type: Object }) + options: ISourceOptions = {}; + + @property({ type: Boolean, attribute: "fullscreen" }) + fullscreen = true; + + protected onParticlesLoaded(e: CustomEvent) { + console.log("Container pronto:", e.detail.id); + } + + render() { + return html` + + + `; + } +} +``` + +## Atualizações Dinâmicas + +Como o `` usa propriedades reativas do Lit, alterar a propriedade `options` atualiza automaticamente as partículas: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("dynamic-particles") +class DynamicParticles extends LitElement { + @state() + private theme: "light" | "dark" = "dark"; + + private get options(): ISourceOptions { + return this.theme === "dark" + ? { + background: { color: "#0d1117" }, + particles: { color: { value: "#58a6ff" } }, + } + : { + background: { color: "#ffffff" }, + particles: { color: { value: "#0969da" } }, + }; + } + + private toggleTheme() { + this.theme = this.theme === "dark" ? "light" : "dark"; + } + + render() { + return html` + + + `; + } +} +``` + +O componente observa a propriedade `options` e chama `refresh()` internamente sempre que ela muda, atualizando perfeitamente a configuração das partículas em tempo de execução. diff --git a/websites/website/docs/pt/guides/nextjs.md b/websites/website/docs/pt/guides/nextjs.md new file mode 100644 index 00000000000..d6ee9db4d33 --- /dev/null +++ b/websites/website/docs/pt/guides/nextjs.md @@ -0,0 +1,492 @@ +--- +title: Integração Next.js +description: Guia passo a passo para integrar tsParticles em uma aplicação Next.js usando o App Router. +--- + +# Integração Next.js + +Este guia aborda a integração de tsParticles em um projeto Next.js usando o **App Router** (Next.js 13+). Para o Pages Router legado, veja a seção [Pages Router Legado](#pages-router-legado) no final. + +## Instalação + +Instale o wrapper `@tsparticles/react` e o motor completo `tsparticles` (ou um bundle slim para builds menores): + +```bash +npm install @tsparticles/react tsparticles +``` + +Se preferir o bundle menor `@tsparticles/slim`: + +```bash +npm install @tsparticles/react @tsparticles/slim +``` + +## Uso Básico (App Router) + +Os componentes do App Router do Next.js são do lado do servidor por padrão. Como o tsParticles requer a API `canvas` do navegador, você deve marcar o componente com a diretiva `"use client"`. + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesBackground() { + const particlesLoaded = useCallback((container?: Container) => { + console.log("Partículas carregadas", container); + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }), + [], + ); + + return ; +} +``` + +Crie isso como `components/particles-background.tsx` e importe-o em qualquer página ou layout. Como o arquivo começa com `"use client"`, ele será renderizado no cliente — exatamente onde o tsParticles precisa estar. + +## Alternância de Tema + +Combine tsParticles com alternadores de tema do Next.js derivando as opções do estado atual do tema: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useMemo, useState, useCallback } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ThemeAwareParticles() { + const [theme, setTheme] = useState<"light" | "dark">("dark"); + + const toggleTheme = useCallback(() => { + setTheme((t) => (t === "dark" ? "light" : "dark")); + }, []); + + const particlesLoaded = useCallback((_container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { + color: theme === "dark" ? "#000000" : "#ffffff", + }, + particles: { + color: { value: theme === "dark" ? "#ffffff" : "#000000" }, + number: { value: 100 }, + links: { + enable: true, + color: theme === "dark" ? "#ffffff" : "#000000", + }, + move: { enable: true }, + }, + }), + [theme], + ); + + return ( + <> + + + + ); +} +``` + +O objeto `options` é recriado via `useMemo` sempre que `theme` muda, então o canvas é atualizado automaticamente. + +## Efeito Confete + +Use o `@tsparticles/preset-confetti` para disparar confetes comemorativos em eventos como cliques em botões: + +```bash +npm install @tsparticles/preset-confetti +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Container, ISourceOptions, Engine } from "@tsparticles/engine"; + +export default function ConfettiButton() { + const [active, setActive] = useState(false); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadConfettiPreset(engine); + }, []); + + const particlesLoaded = useCallback( + async (container?: Container) => { + if (active && container) { + await container.play(); + } + }, + [active], + ); + + const options: ISourceOptions = useMemo( + () => ({ + preset: "confetti", + fullScreen: { zIndex: 1000 }, + }), + [], + ); + + const handleCelebrate = useCallback(() => { + setActive(true); + setTimeout(() => setActive(false), 5000); + }, []); + + return ( + <> + {active && } + + + ); +} +``` + +O callback `init` carrega o preset de confete no motor antes que as partículas sejam criadas. + +## Efeito Fogos de Artifício + +Da mesma forma, o preset de fogos de artifício cria um espetáculo de fogos: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; +import type { Container, Engine } from "@tsparticles/engine"; + +export default function FireworksBackground() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFireworksPreset(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options = useMemo( + () => ({ + preset: "fireworks" as const, + fullScreen: { zIndex: -1 }, + background: { + color: "#000", + }, + }), + [], + ); + + return ; +} +``` + +## Exemplo TypeScript Completo com Referência ao Container + +Acesse a instância `Container` para controlar a animação programaticamente (tocar, pausar, destruir, exportar imagem): + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +export default function ControllableParticles() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFull(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + fpsLimit: 120, + interactivity: { + events: { + onClick: { enable: true, mode: "push" }, + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + push: { quantity: 4 }, + repulse: { distance: 100 }, + }, + }, + particles: { + color: { value: "#ff0000" }, + links: { + enable: true, + color: "#ff0000", + distance: 150, + }, + move: { enable: true, speed: 2 }, + number: { value: 60 }, + size: { value: { min: 1, max: 5 } }, + }, + }), + [], + ); + + const handlePause = useCallback(() => { + containerRef.current?.pause(); + }, []); + + const handlePlay = useCallback(() => { + containerRef.current?.play(); + }, []); + + return ( +
+ +
+ + +
+
+ ); +} +``` + +Pontos principais: + +- `particlesInit` carrega as funcionalidades do motor (executa apenas uma vez por montagem do componente). +- `particlesLoaded` é disparado toda vez que o container é totalmente inicializado. +- `containerRef` mantém a instância `Container` para que você possa chamar seus métodos depois. + +## Performance: useMemo e useCallback + +Sempre envolva opções estáticas ou raramente alteradas em `useMemo` e handlers de eventos em `useCallback` para evitar re-renderizações desnecessárias do canvas: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function PerformanceExample() { + const [particlesCount, setParticlesCount] = useState(80); + + // Callback estável — nunca recria a menos que as deps mudem + const particlesLoaded = useCallback((container?: Container) => { + console.log("Container pronto", container?.id); + }, []); + + // Objeto de opções estável — previne reinicialização do canvas + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: particlesCount }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [particlesCount], + ); + + return ( +
+ + +
+ ); +} +``` + +Sem essas otimizações, cada re-renderização do pai criaria um novo objeto `options`, fazendo com que o canvas fosse recriado. + +## Integração em Página + +Adicione um fundo de partículas ao layout de uma página sem afetar o conteúdo da página: + +```tsx +// app/layout.tsx (componente servidor) +import dynamic from "next/dynamic"; + +const ParticlesBackground = dynamic(() => import("@/components/particles-background"), { ssr: false }); + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + +
{children}
+ + + ); +} +``` + +Use `dynamic()` com `ssr: false` para garantir que o componente nunca execute durante a renderização no servidor. O canvas de partículas fica atrás do conteúdo principal via CSS `z-index`. + +## Múltiplas Instâncias + +Você pode renderizar vários componentes `Particles` independentes na mesma página, cada um com sua própria configuração: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +function ParticlesGallery() { + const loaded = useCallback((c?: Container) => {}, []); + + const redOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#1a0000" }, + particles: { + color: { value: "#ff0000" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + const blueOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#00001a" }, + particles: { + color: { value: "#0000ff" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + return ( +
+ + +
+ ); +} +``` + +Cada componente `Particles` cria um canvas independente com seu próprio loop de animação. Defina `fullScreen: false` e dê a cada um uma altura fixa para que coexistam no fluxo do documento. + +## Pages Router Legado + +Se você está usando o **Pages Router** do Next.js (diretório `pages/`), a abordagem é similar mas sem a diretiva `"use client"`. Em vez disso, você pode usar uma importação dinâmica no componente da página: + +```tsx +// pages/index.tsx +import dynamic from "next/dynamic"; +import type { NextPage } from "next"; + +const ParticlesComponent = dynamic(() => import("../components/particles-component"), { ssr: false }); + +const Home: NextPage = () => { + return ( +
+ +

Bem-vindo

+
+ ); +}; + +export default Home; +``` + +O componente em si (`components/particles-component.tsx`) é um componente React comum: + +```tsx +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesComponent() { + const particlesLoaded = useCallback((container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 80 }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [], + ); + + return ; +} +``` + +Note que o Pages Router não requer `"use client"` porque os componentes da página já são renderizados no cliente por padrão. + +## Solução de Problemas + +| Sintoma | Causa | Correção | +| ------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------- | +| Página em branco | SSR renderizando um módulo dependente de canvas | Use `dynamic(..., { ssr: false })` ou envolva em um componente cliente | +| Canvas não aparecendo | Container com altura zero | Defina `fullScreen: { zIndex: -1 }` ou dê dimensões explícitas | +| Mudança de opções não refletida | Nova referência de objeto não criada | Use `useMemo` com array de dependências adequado | +| Preset não funcionando | Preset não carregado antes da inicialização do container | Chame `loadXPreset(engine)` dentro do callback `init` | + +## Próximos Passos + +- Navegue pelas [Demonstrações Interativas](/demos/) para configurações prontas. +- Leia a [Referência de Opções](/options/) para cada parâmetro disponível. +- Veja a página de [Presets](/demos/presets) para mais presets pré-construídos como neve, estrelas e vaga-lumes. diff --git a/websites/website/docs/pt/guides/nuxt.md b/websites/website/docs/pt/guides/nuxt.md new file mode 100644 index 00000000000..273b0a33e65 --- /dev/null +++ b/websites/website/docs/pt/guides/nuxt.md @@ -0,0 +1,463 @@ +--- +title: Integração Nuxt +description: Guia passo a passo para integrar tsParticles em uma aplicação Nuxt 3 / Nuxt 4. +--- + +# Integração Nuxt + +Este guia aborda a integração de tsParticles em um projeto **Nuxt 3** (e Nuxt 4) usando o wrapper oficial `@tsparticles/vue3`. O Nuxt executa tanto no servidor quanto no cliente, então você deve proteger os componentes de partículas contra SSR. + +## Instalação + +Instale o wrapper Vue 3 e o bundle do motor de sua escolha: + +```bash +npm install @tsparticles/vue3 tsparticles +``` + +Para um bundle menor, instale `@tsparticles/slim` em vez de `tsparticles`: + +```bash +npm install @tsparticles/vue3 @tsparticles/slim +``` + +## Uso Básico + +O Nuxt renderiza componentes no servidor por padrão. Como o tsParticles precisa da API `canvas` do navegador, você deve envolver o componente `` em uma tag ``: + +```vue + + + + + +``` + +O wrapper `` garante que o componente `` seja montado apenas no navegador, prevenindo incompatibilidades de hidratação. + +## Configuração + +Use o tipo `ISourceOptions` completo para configuração type-safe. Você pode definir suas opções inline ou importá-las de um arquivo de configuração separado: + +```vue + +``` + +## Efeito Neve + +Crie um efeito de queda de neve usando o preset snow: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +Como o preset é carregado com `await` de nível superior no ` +``` + +Modos de interação disponíveis incluem: `grab`, `bubble`, `connect`, `repulse`, `push`, `remove`, `attract` e `slow`. + +## Manipulação de Eventos + +O componente `` emite vários eventos de ciclo de vida: + +```vue + + + +``` + +| Evento | Payload | Descrição | +| -------------------- | ----------- | ------------------------------------------------------------------ | +| `@particles-init` | `Engine` | Dispara uma vez quando o motor tsParticles inicializa | +| `@particles-loaded` | `Container` | Dispara toda vez que o container termina de carregar ou recarregar | +| `@particles-destroy` | nenhum | Dispara quando o container é destruído | + +## Exemplo TypeScript Completo + +Um componente completo e tipado com importações explícitas e consciência de ciclo de vida: + +```vue + + + + + +``` + +## Integração em Página + +Adicione um fundo de partículas a uma página Nuxt específica colocando o componente no template da página: + +```vue + + + + + +``` + +Se quiser partículas em **todas** as páginas, adicione o componente a `layouts/default.vue` em vez de páginas individuais. + +## Notas sobre Nuxt 4 + +O Nuxt 4 mantém compatibilidade retroativa com os padrões `` e ` +``` + +## Solução de Problemas + +| Sintoma | Causa | Correção | +| ----------------------------------- | ---------------------------------------------------- | --------------------------------------------------------------------- | +| Tela em branco / erro de hidratação | `` renderizado no servidor | Envolva em `` | +| Preset não tem efeito | Preset não carregado antes da montagem do componente | Chame `loadXPreset()` com await de nível superior no ` + +``` + +O motor inicializa uma vez e é compartilhado entre todas as instâncias de `` na sua aplicação. + +--- + +## Uso Básico + +Após inicializar o motor, use o componente `` no seu template. Passe a configuração como um objeto de opções em formato JSON ou uma referência a uma propriedade do seu componente. + +```html + + + + + +``` + +--- + +## Renderização Condicional + +Use a diretiva `if={}` do Riot com uma propriedade de estado para adiar a renderização do componente de partículas até que o motor tenha terminado de inicializar. Isso evita mudanças de layout e garante que o componente receba um motor pronto. + +```html + + + + + +``` + +Chamar `this.update()` aciona uma re-renderização para que a tag `` apareça quando a promise resolver. + +--- + +## Uso de Presets + +O pacote `@tsparticles/configs` fornece configurações pré-construídas para efeitos comuns como confete, fogos de artifício, neve e estrelas. Use-os diretamente como seu objeto de opções. + +```html + + + + + +``` + +Os presets disponíveis incluem `basic`, `confetti`, `fireworks`, `snow`, `stars` e mais. Cada preset requer que seu pacote de preset correspondente seja carregado no callback do motor. Por exemplo, `configs.fireworks` requer `loadFireworksPreset`. + +--- + +## Configuração Personalizada + +Construa uma configuração personalizada com interatividade, múltiplas formas e opções de animação avançadas. + +```html + + + + + +``` + +--- + +## Componente Completo + +Abaixo está um arquivo `.riot` completo que une tudo: inicialização do motor em `onBeforeMount`, renderização condicional com estado, uma configuração rica com interatividade e um callback `particlesLoaded` através do suporte integrado do componente para eventos carregados. + +```html + +
+

tsParticles + Riot.js

+ + {#if state.particlesInitialized} + + {:else} +

Carregando motor de partículas...

+ {/if} +
+ + + + +
+``` + +--- + +Você tem agora tudo que precisa para integrar tsParticles em uma aplicação Riot.js. Cada exemplo é autocontido e pronto para ser copiado para o seu projeto. diff --git a/websites/website/docs/pt/guides/solid.md b/websites/website/docs/pt/guides/solid.md new file mode 100644 index 00000000000..f88a2ad7645 --- /dev/null +++ b/websites/website/docs/pt/guides/solid.md @@ -0,0 +1,512 @@ +--- +title: Integração SolidJS +description: Guia passo a passo para integrar tsParticles em uma aplicação SolidJS usando o wrapper oficial @tsparticles/solid. +--- + +# Integração SolidJS + +Este guia aborda a integração de tsParticles em um projeto **SolidJS** usando o wrapper oficial `@tsparticles/solid`. O modelo de reatividade de grão fino do SolidJS funciona bem com tsParticles — mudanças nas opções acionam atualizações direcionadas no canvas sem reinicialização completa. + +## Instalação + +Instale o wrapper SolidJS e o bundle do motor de sua escolha: + +```bash +npm install @tsparticles/solid tsparticles +``` + +Para um bundle menor, use `@tsparticles/slim`: + +```bash +npm install @tsparticles/solid @tsparticles/slim +``` + +## Uso Básico + +SolidJS é executado inteiramente no navegador (sem SSR), então você não precisa se proteger contra renderização no servidor. No entanto, o motor deve ser inicializado assincronamente antes de renderizar partículas. + +Use `initParticlesEngine` dentro de `onMount` para carregar as funcionalidades do motor, então renderize condicionalmente o componente `` com ``: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [initialized, setInitialized] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setInitialized(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +O componente `` garante que o elemento `` seja inserido no DOM apenas após o motor estar pronto. + +## Inicialização do Motor + +A função `initParticlesEngine` aceita um callback que recebe a instância `Engine`. Use este callback para registrar as funcionalidades que sua configuração necessita: + +```tsx +import { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import { loadSlim } from "@tsparticles/slim"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Engine } from "@tsparticles/engine"; + +// Mínimo — apenas formas básicas e movimento +initParticlesEngine((engine: Engine) => loadSlim(engine)).then(() => { + console.log("Motor pronto (slim)"); +}); + +// Completo — todas as funcionalidades incluídas +initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => { + console.log("Motor pronto (completo)"); +}); + +// Apenas preset — apenas as funcionalidades necessárias para um preset específico +initParticlesEngine((engine: Engine) => loadConfettiPreset(engine)).then(() => { + console.log("Preset confetti carregado"); +}); +``` + +Chame `initParticlesEngine` uma vez na sua aplicação — tipicamente no `onMount` do componente raiz. A instância do motor é armazenada em cache, então chamadas subsequentes retornam imediatamente. + +## Renderização Condicional + +Use o fluxo de controle `` do SolidJS para adiar a renderização até que o motor esteja inicializado: + +```tsx +import { createSignal, Show, onMount } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import type { Engine } from "@tsparticles/engine"; +import type { Component } from "solid-js"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + Carregando partículas...

}> + +
+ ); +}; +``` + +A prop `fallback` mostra um indicador de carregamento enquanto o motor inicializa. + +## Uso de Presets + +Use `@tsparticles/configs` para configurações rápidas e pré-definidas: + +```bash +npm install @tsparticles/configs +``` + +```tsx +import configs from "@tsparticles/configs"; +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + +
+ + +
+
+ ); +}; + +export default App; +``` + +Configurações disponíveis incluem: `basic`, `bubbles`, `snow`, `stars`, `fireworks`, `confetti`, `links` e mais. + +## Partículas Interativas + +Adicione interações de clique e hover configurando a seção `interactivity`: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 60 }, + links: { enable: true, distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 4 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +- **Modos de hover**: `grab`, `bubble`, `repulse`, `attract`, `slow`, `connect` +- **Modos de clique**: `push`, `remove`, `repulse`, `bubble`, `attract`, `pause` + +## Configuração Personalizada + +Uma configuração personalizada completa com múltiplas formas de partículas, paletas de cores e configurações de movimento: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0a0a23" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { enable: true, rotateX: 600, rotateY: 1200 }, + }, + number: { + value: 40, + density: { enable: true }, + }, + opacity: { + value: { min: 0.3, max: 0.8 }, + animation: { + enable: true, + speed: 0.5, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + animation: { + enable: true, + speed: 2, + sync: false, + }, + }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.3, + width: 1, + }, + shape: { + type: ["circle", "square", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + twinkle: { + particles: { + enable: true, + frequency: 0.05, + opacity: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "bubble" }, + }, + modes: { + repulse: { distance: 120 }, + bubble: { distance: 200, size: 10, opacity: 0.8 }, + }, + }, + detectRetina: true, + }; + + return ( + + + + ); +}; + +export default App; +``` + +## Exemplo TypeScript Completo + +Um componente tipado completo com referência ao container, inicialização do motor e controles manuais: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [container, setContainer] = createSignal(undefined); + const [paused, setPaused] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#1a1a2e" }, + particles: { + color: { value: "#e94560" }, + number: { value: 80 }, + links: { enable: true, color: "#e94560", distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 5 } }, + }, + }; + + const particlesLoaded = (c: Container) => { + setContainer(c); + }; + + const togglePause = () => { + const c = container(); + if (c) { + if (paused()) { + c.play(); + } else { + c.pause(); + } + setPaused(!paused()); + } + }; + + return ( + + + + + ); +}; + +export default App; +``` + +## Opções Dinâmicas com Signals + +Um dos pontos fortes do SolidJS é a reatividade de grão fino — você pode usar signals para controlar as opções das partículas e o canvas atualizará eficientemente: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [color, setColor] = createSignal("#ff0000"); + const [particleCount, setParticleCount] = createSignal(60); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + // options é um objeto normal — será lido reativamente através + // do rastreamento interno do componente Particle + const options = (): ISourceOptions => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#000" }, + particles: { + color: { value: color() }, + number: { value: particleCount() }, + links: { enable: true, color: color() }, + move: { enable: true }, + }, + }); + + return ( + + {}} /> +
+ + +
+
+ ); +}; + +export default App; +``` + +Como `options` é uma função que acessa signals, toda vez que `color()` ou `particleCount()` muda, o componente `` recebe um novo objeto de opções e aplica apenas as propriedades alteradas ao canvas existente. + +## Preset com Sobrescritas Personalizadas + +Carregue um preset e depois mescle sobrescritas personalizadas para um efeito sob medida: + +```tsx +import { loadSnowPreset } from "@tsparticles/preset-snow"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadSnowPreset(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + preset: "snow", + fullScreen: { zIndex: -1 }, + background: { color: "#0d0d2b" }, + particles: { + // Sobrescrever a cor da neve para azul + color: { value: "#88ccff" }, + // Aumentar o número de flocos + number: { value: 300 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +O preset fornece valores padrão para cada opção, e suas sobrescritas são mescladas por cima — você só precisa especificar as propriedades que deseja alterar. + +## Solução de Problemas + +| Sintoma | Causa | Correção | +| ------------------------------- | ----------------------------------------------- | ----------------------------------------------------------------------------- | +| Elemento DOM em branco | Motor não inicializado antes da renderização | Envolva `` em `` | +| Nenhuma partícula visível | Faltando `move.enable` ou `number.value` | Certifique-se de `particles.move.enable: true` e `particles.number.value > 0` | +| Canvas atrás do conteúdo | Faltando `zIndex` no fullScreen | Use `fullScreen: { zIndex: -1 }` | +| Mudança de opções não refletida | Referência do objeto não mudando | Envolva opções em uma função ou store; evite objetos estáticos | +| Motor não encontrado | Faltando importação de `loadFull` ou `loadSlim` | Instale `tsparticles` ou `@tsparticles/slim` e chame `loadFull(engine)` | + +## Próximos Passos + +- Explore o [Playground de Configurações](/playground/configs) para configurações prontas para uso. +- Leia a [Referência de Opções](/options/) para a lista completa de parâmetros. +- Navegue pelo [código fonte do SolidJS](https://github.com/tsparticles/solid) no GitHub para detalhes do wrapper. diff --git a/websites/website/docs/pt/guides/stencil.md b/websites/website/docs/pt/guides/stencil.md new file mode 100644 index 00000000000..a9ad4724e6a --- /dev/null +++ b/websites/website/docs/pt/guides/stencil.md @@ -0,0 +1,359 @@ +--- +title: Guia Stencil +description: Guia completo para integrar tsParticles com componentes Stencil. +--- + +# Guia Stencil + +## Índice + +1. [Instalação](#instalação) +2. [Registro de Elementos Personalizados](#registro-de-elementos-personalizados) +3. [Uso Básico](#uso-básico) +4. [Inicialização do Motor](#inicialização-do-motor) +5. [Configuração Personalizada](#configuração-personalizada) +6. [Ciclo de Vida do Componente](#ciclo-de-vida-do-componente) +7. [Exemplo TypeScript](#exemplo-typescript) + +--- + +## Instalação + +Instale o wrapper Stencil e o motor tsParticles via npm: + +```bash +npm install @tsparticles/stencil tsparticles +``` + +Opcionalmente instale um bundle de preset para reduzir a configuração manual: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Registro de Elementos Personalizados + +O pacote `@tsparticles/stencil` fornece uma função `defineCustomElements` que registra o elemento personalizado `` no navegador. Chame-a uma vez antes de usar o componente em qualquer lugar da sua aplicação. + +```tsx +import { defineCustomElements } from "@tsparticles/stencil/loader"; + +// Registrar o elemento +defineCustomElements(); +``` + +Para projetos Stencil que usam lazy-loading, chame isso dentro de `componentWillLoad` ou no componente raiz da sua aplicação para garantir que o elemento esteja disponível antes da renderização. + +--- + +## Uso Básico + +Uma vez que o elemento personalizado está registrado, você pode usar `` no seu JSX com uma prop `options` e um callback `init` para carregar as funcionalidades necessárias do motor. + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +@Component({ tag: "my-particles" }) +export class MyParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## Inicialização do Motor + +A prop `init` recebe a instância do motor e permite carregar as funcionalidades necessárias. Este é o local recomendado para chamar `loadSlim`, `loadFull` ou plugins individuais de atualizadores/interações. + +```tsx +import { loadSlim } from "@tsparticles/slim"; +import { loadFull } from "tsparticles"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// Opção A: leve (círculos, movimento básico, links) +init={async engine => { await loadSlim(engine); }} + +// Opção B: conjunto completo de funcionalidades (todas as formas, efeitos, presets) +init={async engine => { await loadFull(engine); }} + +// Opção C: presets (confete, fogos de artifício, neve, estrelas) +init={async engine => { await loadConfettiPreset(engine); }} +``` + +A instância do motor também é acessível após a inicialização através do atributo `container-id`, permitindo controlar programaticamente o sistema de partículas posteriormente, se necessário. + +--- + +## Configuração Personalizada + +Abaixo está uma configuração completa com interatividade, múltiplos tipos de forma e modos de hover/clique. + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const fullOptions: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { + color: "#0f0f23", + }, +}; + +@Component({ tag: "app-particles" }) +export class AppParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## Ciclo de Vida do Componente + +No Stencil, o hook de ciclo de vida recomendado para configuração única é `componentWillLoad`. Use-o para registrar elementos personalizados e gerenciar o estado de inicialização para que o componente `` renderize apenas quando o motor estiver preparado. + +```tsx +import { Component, h, State } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ tag: "app-root" }) +export class AppRoot { + @State() private engineReady = false; + + private options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { + enable: true, + speed: 1, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#1a1a2e" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.engineReady = true; + } + + render() { + return ( +
+

tsParticles + Stencil

+ {this.engineReady && ( + { + await loadSlim(engine); + }} + /> + )} +
+ ); + } +} +``` + +Usar `@State()` garante que o componente re-renderize quando o motor ficar pronto, e a renderização condicional impede que o container de partículas monte antes que o elemento personalizado seja definido. + +--- + +## Exemplo TypeScript + +Aqui está um componente de aplicação Stencil completo e tipado que integra tsParticles com o preset slim, interatividade hover e um tema escuro personalizado. + +```tsx +import { Component, h, State, Prop } from "@stencil/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ + tag: "app-home", + styleUrl: "app-home.css", + shadow: true, +}) +export class AppHome { + @State() private initialized = false; + + @Prop() readonly title: string = "Bem-vindo"; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.initialized = true; + } + + private handleInit = async (engine: Engine): Promise => { + await loadSlim(engine); + }; + + private handleLoaded = async (container?: Container): Promise => { + this.container = container; + console.log("Container de partículas carregado:", container?.id); + }; + + render() { + return ( +
+

{this.title}

+

Desenvolvido com tsParticles e Stencil

+ + {this.initialized && ( + + )} +
+ ); + } +} +``` + +O evento `particlesLoaded` é disparado quando o primeiro frame é renderizado, dando acesso à instância `Container` para controle programático (tocar, pausar, parar, alternar temas). + +--- + +Você tem agora tudo que precisa para integrar tsParticles em uma aplicação Stencil. Cada exemplo é autocontido e pronto para ser copiado para o seu projeto. diff --git a/websites/website/docs/pt/guides/svelte.md b/websites/website/docs/pt/guides/svelte.md new file mode 100644 index 00000000000..1128f2b159e --- /dev/null +++ b/websites/website/docs/pt/guides/svelte.md @@ -0,0 +1,580 @@ +--- +title: Integração Svelte +description: Guia passo a passo para integrar tsParticles em aplicações Svelte e SvelteKit usando @tsparticles/svelte. +--- + +# Integração Svelte + +O pacote `@tsparticles/svelte` fornece um componente Svelte nativo para tsParticles. Este guia aborda Svelte (com Vite) e SvelteKit, incluindo opções reativas, manipulação de eventos e múltiplas instâncias. + +--- + +## Instalação + +```bash +npm install @tsparticles/svelte @tsparticles/engine +``` + +Para o bundle completo ou presets: + +```bash +npm install tsparticles +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +``` + +--- + +## Uso Básico + +```svelte + + + +``` + +--- + +## Inicialização do Motor + +Passe um handler de evento `on:init` para carregar os plugins e presets que sua aplicação precisa: + +```svelte + + + +``` + +Alternativamente, use o utilitário `initParticlesEngine` antes da montagem: + +```svelte + + +{#if ready} + +{/if} +``` + +--- + +## Efeito Neve + +```bash +npm install @tsparticles/preset-snow +``` + +```svelte + + + +``` + +Personalize o comportamento do preset mesclando opções adicionais: + +```svelte + +``` + +--- + +## Efeito Estrelas + +```bash +npm install @tsparticles/preset-stars +``` + +```svelte + + + +``` + +--- + +## Partículas Interativas + +Adicione interatividade de hover e clique do mouse: + +```svelte + + + +``` + +--- + +## Manipulação de Eventos + +```svelte + + +
+ + + +
+ + +``` + +| Evento | Detalhe | Dispara | +| -------------------- | ----------- | ---------------------------------------- | +| `on:init` | `Engine` | Após o motor ser inicializado | +| `on:particlesLoaded` | `Container` | Após o container estar totalmente pronto | + +--- + +## Exemplo TypeScript + +Componente completo tipado: + +```svelte + + + +``` + +--- + +## Opções Dinâmicas + +Opções reativas atualizam as partículas sem recriar a instância: + +```svelte + + +
+ +
+ + +``` + +A declaração reativa `$:` recalcula `options` sempre que `color` muda, e o componente `Particles` captura a nova configuração automaticamente. + +--- + +## Múltiplas Instâncias + +Renderize vários sistemas de partículas independentes na mesma página: + +```svelte + + +
+
+ +
+
+ +
+
+``` + +Cada componente `` recebe seu próprio `id`, canvas e contexto do motor. + +--- + +## Uso com SvelteKit + +No SvelteKit, o canvas requer o ambiente do navegador. Desabilite SSR para o componente: + +```svelte + + +{#if Component} + +{/if} +``` + +Ou envolva a importação em um componente client-side. Para SvelteKit 2+, você também pode usar as exclusões SSR do `vite-plugin-svelte`. + +--- + +## Referência da API + +| Prop | Tipo | Padrão | Descrição | +| --------- | ---------------- | --------------- | ------------------------------------- | +| `id` | `string` | `"tsparticles"` | ID do elemento canvas | +| `options` | `ISourceOptions` | `{}` | Objeto de configuração das partículas | +| `url` | `string` | — | URL para uma configuração JSON remota | + +| Evento | Detalhe | Descrição | +| -------------------- | ----------- | ----------------------------------------------------------------- | +| `on:init` | `Engine` | Dispara quando o motor é inicializado (use para carregar plugins) | +| `on:particlesLoaded` | `Container` | Dispara quando o container está totalmente pronto | + +--- + +## Solução de Problemas + +- **Canvas não visível** — Certifique-se de que o container pai tenha dimensões explícitas (`height: 100%`, `height: 100vh` ou um valor fixo em pixels). +- **`loadFull is not a function`** — Verifique se `tsparticles` está instalado e se você está importando `loadFull` de `tsparticles` (não de `@tsparticles/engine`). +- **Reatividade não funcionando** — Certifique-se de que `options` é uma variável reativa (`$:` ou `let` vinculada a uma fonte reativa). Valores `const` comuns não serão atualizados. +- **SvelteKit tela em branco** — Importe `@tsparticles/svelte` dinamicamente ou use o guard `browser` como mostrado na seção SvelteKit acima. +- **Erros TypeScript para `event.detail`** — Use os tipos `CustomEvent` e `CustomEvent` para os handlers de evento. diff --git a/websites/website/docs/pt/guides/vanilla.md b/websites/website/docs/pt/guides/vanilla.md new file mode 100644 index 00000000000..6b64bb20128 --- /dev/null +++ b/websites/website/docs/pt/guides/vanilla.md @@ -0,0 +1,889 @@ +--- +title: Guia Vanilla JS +description: Guia completo para integrar tsParticles com JavaScript puro. +--- + +# Guia Vanilla JS + +## Índice + +1. [Primeiros Passos](#primeiros-passos) +2. [Partículas Básicas](#partículas-básicas) +3. [Efeito Confete](#efeito-confete) +4. [Efeito Fogos de Artifício](#efeito-fogos-de-artifício) +5. [Efeito Fitas](#efeito-fitas) +6. [Efeito Neve](#efeito-neve) +7. [Efeito Rede / Links](#efeito-rede-links) +8. [Efeito Estrelas](#efeito-estrelas) +9. [Configuração Personalizada](#configuração-personalizada) +10. [Múltiplos Contêineres](#múltiplos-contêineres) +11. [Controles Dinâmicos](#controles-dinâmicos) + +--- + +## Primeiros Passos + +### CDN (início rápido) + +Adicione um `
` placeholder e tags de script no seu HTML. Você precisa pelo menos do motor + um pacote, e deve chamar o loader antes de `tsParticles.load()`. + +```html + + + + + + tsParticles – Getting Started + + + +
+ + + + + + +``` + +### npm + +```bash +npm install @tsparticles/engine @tsparticles/slim +``` + +Em seguida, importe e use: + +```javascript +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +(async () => { + await loadSlim(tsParticles); + + await tsParticles.load({ + id: "tsparticles", + options: { + /* ... */ + }, + }); +})(); +``` + +> **Nota:** `@tsparticles/engine` sozinho não desenha nada. Você deve instalar um pacote (`@tsparticles/slim` recomendado) ou plugins individuais para obter formas visíveis. + +--- + +## Partículas Básicas + +Uma configuração mínima que renderiza 100 partículas com formato circular, cores aleatórias e movimento suave. Na v4, as cores das partículas são definidas via `paint` em vez da antiga propriedade `color`. + +```html + + + + + + Basic Particles + + + +
+ + + + + + +``` + +--- + +## Efeito Confete + +Use o pacote dedicado `@tsparticles/confetti` para uma rajada de confete com uma única chamada de função. + +```html + + + + + + Confetti + + + + + + + + + +``` + +--- + +## Efeito Fogos de Artifício + +Um show de fogos de artifício usando o pacote dedicado `@tsparticles/fireworks` com efeitos sonoros. + +```html + + + + + + Fireworks + + + + + + + +``` + +--- + +## Efeito Fitas + +Use o pacote dedicado `@tsparticles/ribbons` para animações de fitas fluídas que reagem à posição do mouse. + +```html + + + + + + Ribbons + + + + + + + +``` + +--- + +## Efeito Neve + +Flocos de neve caindo suavemente usando o catálogo de predefinições `@tsparticles/configs`. + +```html + + + + + + Snow Effect + + + +
+ + + + + + + +``` + +Alternativamente, usando o pacote de predefinição independente: + +```html + + + + +``` + +--- + +## Efeito Rede / Links + +Um visual clássico de nós conectados com interatividade do mouse. O pacote `@tsparticles/slim` inclui a interação de links e o modo de agarrar do mouse. + +```html + + + + + + Network / Links + + + +
+ + + + + + +``` + +--- + +## Efeito Estrelas + +Um céu estrelado noturno usando o catálogo de predefinições `@tsparticles/configs`. + +```html + + + + + + Stars Effect + + + +
+ + + + + + + +``` + +Alternativamente, usando o pacote de predefinição independente: + +```html + + + + +``` + +--- + +## Configuração Personalizada + +Construa uma configuração do zero com fundo gradiente, efeitos interativos de hover e múltiplos tipos de forma usando o pacote slim. + +```html + + + + + + Custom Config + + + +

Custom Configuration

+
+ + + + + + +``` + +--- + +## Múltiplos Contêineres + +Execute múltiplas instâncias independentes de partículas na mesma página, cada uma com sua própria configuração. + +```html + + + + + + Multiple Containers + + + +
+
+
+
+ + + + + + +``` + +--- + +## Controles Dinâmicos + +Inicie, pare, pause e alterne temas programaticamente em tempo de execução. + +```html + + + + + + Dynamic Controls + + + +
+
+ + + + + + +
+ + + + + + +``` + +--- + +Agora você cobriu todos os principais padrões de integração Vanilla JS para tsParticles v4. Cada exemplo é um arquivo HTML independente que você pode abrir no seu navegador para ver tsParticles em ação. diff --git a/websites/website/docs/pt/guides/vue3.md b/websites/website/docs/pt/guides/vue3.md new file mode 100644 index 00000000000..08971d495d7 --- /dev/null +++ b/websites/website/docs/pt/guides/vue3.md @@ -0,0 +1,622 @@ +--- +title: Integração Vue 3 +description: Guia passo a passo para integrar tsParticles em aplicações Vue 3 usando @tsparticles/vue3. +--- + +# Integração Vue 3 + +O pacote `@tsparticles/vue3` fornece um componente Vue 3 nativo e sistema de plugins para tsParticles. Este guia aborda tudo, desde a configuração básica até padrões avançados como alternância dinâmica de temas e presets personalizados. + +--- + +## Instalação + +```bash +npm install @tsparticles/vue3 @tsparticles/engine +``` + +Opcionalmente instale um preset ou o bundle completo: + +```bash +# Bundle completo (todas as funcionalidades) +npm install tsparticles + +# Presets específicos +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars + +# Configurações utilitárias +npm install @tsparticles/configs +``` + +--- + +## Uso Básico + +Registre o plugin no ponto de entrada da sua aplicação, depois use o componente `` em qualquer lugar. + +### Entrada da aplicação (`main.ts`) + +```typescript +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +const app = createApp(App); + +app.use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, +}); + +app.mount("#app"); +``` + +### Componente (`App.vue`) + +```vue + + + +``` + +--- + +## Usando `particlesInit` com o Componente + +Se preferir não usar o plugin global, passe um callback `init` diretamente: + +```vue + + + +``` + +--- + +## Eventos + +O componente emite vários eventos de ciclo de vida: + +```vue + + + +``` + +--- + +## Efeito Confete + +Use o preset confetti para celebrações: + +```bash +npm install @tsparticles/preset-confetti +``` + +```vue + + + +``` + +Para uma explosão única, carregue o preset e depois chame `tsParticles.load()` programaticamente dentro de um método. + +--- + +## Efeito Fogos de Artifício + +O preset fireworks cria explosões de partículas de alto impacto: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```vue + + + +``` + +> **Dica:** O preset fireworks consome muitos recursos. Acione-o na interação do usuário (ex.: clique de botão) alternando um `v-if` vinculado ao componente. + +--- + +## Efeito Neve + +Simule queda de neve com o preset snow: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +--- + +## Partículas Interativas + +Adicione modos de interatividade de hover e clique: + +```vue + + + +``` + +Modos de interação disponíveis: `grab`, `repulse`, `bubble`, `connect`, `push`, `remove`, `trail`, `attract`, `light`. + +--- + +## Alternância de Tema + +Troque dinamicamente os temas das partículas em tempo de execução atualizando o objeto de opções reativo: + +```vue + + + +``` + +Alternativamente, use a opção de [temas](https://particles.js.org/docs/interfaces/Options_Interfaces_IOptions.IOptions.html#themes) incorporada e a propriedade `theme` no container para alternância sem configuração. + +--- + +## Preset Personalizado do @tsparticles/configs + +O pacote `@tsparticles/configs` exporta objetos de configuração pré-fabricados: + +```bash +npm install @tsparticles/configs +``` + +```vue + + + +``` + +Navegue pelas configurações disponíveis no pacote `@tsparticles/configs` para layouts prontos para uso. + +--- + +## Abordagens de Inicialização do Motor + +Existem duas maneiras de inicializar o motor: + +### 1. Plugin Global (recomendado) + +```typescript +// main.ts +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +createApp(App) + .use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, + }) + .mount("#app"); +``` + +O motor fica então disponível globalmente e todas as instâncias de `` o compartilham. + +### 2. Init no Nível do Componente + +Passe um callback `:init` para cada instância de ``. Útil quando diferentes componentes precisam de diferentes conjuntos de plugins: + +```vue + +``` + +### 3. Particles Provider (Composition API) + +Use o provider para acessar o motor programaticamente: + +```vue + +``` + +--- + +## Named Exports + TypeScript + +Exemplo TypeScript completo com todas as peças juntas: + +```vue + + + +``` + +--- + +## Referência da API + +| Prop | Tipo | Padrão | Descrição | +| --------- | ----------------------------------- | --------------- | ----------------------------------- | +| `id` | `string` | `"tsparticles"` | ID do elemento canvas | +| `options` | `ISourceOptions` | `{}` | Configuração das partículas | +| `init` | `(engine: Engine) => Promise` | — | Callback de inicialização do motor | +| `url` | `string` | — | URL para carregar configuração JSON | + +| Evento | Payload | Descrição | +| ------------------- | ----------- | ---------------------------------------------------- | +| `@particles-loaded` | `Container` | Dispara quando o container é totalmente inicializado | +| `@particles-init` | `Engine` | Dispara após o motor ser inicializado | + +--- + +## Solução de Problemas + +- **Erro: `tsparticles is not defined`** — Certifique-se de que `tsparticles` (ou os presets necessários) sejam carregados dentro do callback `init` antes do componente renderizar. +- **Canvas não aparecendo** — Verifique se o container pai tem uma altura não zero. Adicione uma regra CSS como `#tsparticles { height: 100vh; }`. +- **Problemas de performance** — Reduza `fpsLimit`, diminua `particles.number.value` ou desative `detectRetina` em dispositivos de baixo desempenho. +- **SSR (Nuxt)** — O componente `` é client-side. Envolva-o em `` ou use a diretiva `client:only`. diff --git a/websites/website/docs/pt/guides/webcomponents.md b/websites/website/docs/pt/guides/webcomponents.md new file mode 100644 index 00000000000..41b6ead0af8 --- /dev/null +++ b/websites/website/docs/pt/guides/webcomponents.md @@ -0,0 +1,359 @@ +# Web Components + +Use tsParticles com Web Components nativos através do pacote `@tsparticles/webcomponents`. Esta abordagem não requer framework — apenas JavaScript puro e elementos personalizados. + +## Instalação + +### Via CDN + +Inclua o núcleo tsParticles e o bundle de Web Components: + +```html + + +``` + +### Via npm + Build + +```bash +npm install @tsparticles/webcomponents tsparticles +``` + +Em seguida, importe para o seu bundle JavaScript: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; +``` + +## Inicialização do Motor + +Antes que o elemento `` possa renderizar, o motor deve ser inicializado com as funcionalidades necessárias. Chame `initParticlesEngine` com um callback que carrega os plugins desejados: + +```javascript +import { initParticlesEngine } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +> **Por que `loadFull`?** Ele registra todas as formas integradas (círculo, quadrado, polígono, imagem, etc.), interações (hover, clique) e atualizadores (opacidade, tamanho, cor, etc.). Para um bundle menor, use `tsparticles-slim` ou escolha plugins individuais. + +## Definindo o Elemento Personalizado + +Após a inicialização do motor, registre o elemento personalizado ``: + +```javascript +import { defineParticlesElement } from "@tsparticles/webcomponents"; + +defineParticlesElement(); +``` + +Isso registra a tag `web-particles` no `CustomElementRegistry` do navegador. É seguro chamar múltiplas vezes — registros duplicados são ignorados. + +## Uso Básico + +Uma vez que tanto `initParticlesEngine` quanto `defineParticlesElement` foram executados, use o elemento diretamente no HTML: + +```html + + + + + + tsParticles Web Components + + + + + + + +``` + +## Configuração Personalizada + +O elemento `` aceita configuração via propriedade `options` (objeto JavaScript) ou via JSON no atributo `options`. + +### Via Propriedade JavaScript + +```javascript +const el = document.querySelector("web-particles"); +el.options = { + background: { color: "#000000" }, + fpsLimit: 60, + particles: { + color: { value: ["#ff0000", "#00ff00", "#0000ff"] }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { value: 60 }, + opacity: { value: 0.6 }, + shape: { type: ["circle", "square"] }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + repulse: { distance: 200 }, + push: { quantity: 4 }, + }, + }, +}; +``` + +### Via Atributo HTML (JSON) + +```html + +``` + +> Ao usar o atributo `options`, o valor deve ser JSON válido. A atribuição de propriedade é preferida para configurações complexas. + +## Criação Dinâmica + +Você pode criar elementos `` inteiramente em JavaScript e adicioná-los ao DOM a qualquer momento: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +defineParticlesElement(); + +function createParticles(container, config) { + const el = document.createElement("web-particles"); + el.id = "dynamic-particles"; + el.style.position = "absolute"; + el.style.width = "100%"; + el.style.height = "100%"; + el.style.top = "0"; + el.style.left = "0"; + el.options = config; + container.appendChild(el); + return el; +} + +// Uso +const particles = createParticles(document.body, { + background: { color: "#1a1a2e" }, + particles: { + number: { value: 100 }, + links: { enable: true, color: "#e94560" }, + move: { enable: true, speed: 1 }, + }, +}); +``` + +## Estendendo o Elemento Personalizado + +Você pode subclassificar `ParticlesElement` para criar seu próprio elemento personalizado com configuração embutida: + +```javascript +import { initParticlesEngine, ParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +class MyParticlesBackground extends ParticlesElement { + constructor() { + super(); + this.style.position = "fixed"; + this.style.top = "0"; + this.style.left = "0"; + this.style.width = "100%"; + this.style.height = "100%"; + this.style.zIndex = "-1"; + } + + connectedCallback() { + this.options = { + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true, speed: 2 }, + }, + }; + super.connectedCallback(); + } +} + +customElements.define("my-particles-bg", MyParticlesBackground); +``` + +Uso: + +```html + +``` + +## Acesso e Controle do Container + +O elemento personalizado expõe a instância `Container` do tsParticles para controle imperativo: + +```javascript +const el = document.querySelector("web-particles"); + +// Acessar o container (disponível após connectedCallback) +const container = el.container; +container?.pause(); +container?.play(); + +// Destruir e limpar +el.dispose(); +``` + +## Exemplo Completo + +Uma página HTML completa usando o módulo de Web Components com scripts CDN: + +```html + + + + + + Demo tsParticles Web Components + + + +
+

tsParticles + Web Components

+

Elementos personalizados nativos, sem necessidade de framework.

+
+ + + + + + +``` + +## Referência da API + +| Export / Property | Tipo | Descrição | +| ------------------------------- | ------------------------ | ---------------------------------------------------------------- | +| `initParticlesEngine(callback)` | `function` | Inicializar o motor tsParticles com carregadores de plugins | +| `defineParticlesElement()` | `function` | Registrar o elemento personalizado `` | +| `ParticlesElement` | `class` | Classe base que você pode estender para elementos personalizados | +| `element.options` | `ISourceOptions` | Obter/definir o objeto de configuração das partículas | +| `element.container` | `Container \| undefined` | Referência somente leitura ao `Container` subjacente | +| `element.dispose()` | `function` | Destruir a instância de partículas e limpar recursos | diff --git a/websites/website/docs/pt/guides/wordpress.md b/websites/website/docs/pt/guides/wordpress.md new file mode 100644 index 00000000000..58d91c4585c --- /dev/null +++ b/websites/website/docs/pt/guides/wordpress.md @@ -0,0 +1,314 @@ +--- +title: Guia WordPress +description: Guia completo para integrar tsParticles com WordPress usando o plugin, blocos, shortcodes e integração com temas. +--- + +# Guia WordPress + +## Índice + +1. [Instalação](#instalação) +2. [Ativação do Plugin](#ativação-do-plugin) +3. [Uso de Widget e Bloco](#uso-de-widget-e-bloco) +4. [Uso de Shortcode](#uso-de-shortcode) +5. [Configuração via Filtro PHP](#configuração-via-filtro-php) +6. [Configuração Personalizada via Filtro](#configuração-personalizada-via-filtro) +7. [Integração com Temas](#integração-com-temas) + +--- + +## Instalação + +O plugin tsParticles para WordPress está disponível através do Diretório de Plugins do WordPress. Instale-o diretamente do painel administrativo do WordPress. + +### No Painel WordPress + +1. Navegue até **Plugins → Adicionar Novo** +2. Pesquise por "tsParticles" +3. Clique em **Instalar Agora** no plugin tsParticles +4. Clique em **Ativar** + +### Instalação Manual + +1. Baixe o ZIP do plugin do Diretório de Plugins do WordPress ou da [página de releases](https://github.com/tsparticles/wordpress/releases) +2. Navegue até **Plugins → Adicionar Novo → Enviar Plugin** +3. Escolha o arquivo ZIP e clique em **Instalar Agora** +4. Clique em **Ativar** + +--- + +## Ativação do Plugin + +Uma vez ativado, o plugin registra: + +- Um **bloco Gutenberg** chamado "tsParticles" disponível no inseridor de blocos +- Um **shortcode** `[tsparticles]` para uso no Editor Clássico ou em templates PHP personalizados +- Um **filtro PHP** `tsparticles_options` para desenvolvedores injetarem configuração programaticamente +- Assets front-end (JavaScript e CSS) que são enfileirados apenas quando o bloco ou shortcode está presente na página + +Após a ativação, você pode verificar se o plugin está funcionando visitando **Configurações → tsParticles** na barra lateral do admin WordPress, onde uma página de configurações básicas pode estar disponível dependendo da versão do plugin. + +--- + +## Uso de Widget e Bloco + +O plugin tsParticles adiciona um bloco Gutenberg personalizado para o editor de blocos (WordPress 5.0+). + +### Adicionando o Bloco + +1. Edite qualquer post ou página com o editor de blocos (Gutenberg) +2. Clique no botão **+** (Adicionar Bloco) +3. Pesquise por "tsParticles" ou "Particles" +4. Clique no bloco **tsParticles** para inseri-lo + +### Configurações do Bloco + +Uma vez inserido, o painel de inspeção do bloco (no lado direito) fornece configurações: + +- **ID do Container** — um ID HTML único para o container de partículas (padrão: `tsparticles`) +- **Largura / Altura** — defina dimensões explícitas ou use o modo tela cheia +- **Z-Index** — controla a camada em relação a outro conteúdo +- **Configuração** — cole um objeto JSON de opções para personalizar completamente a aparência das partículas + +Para áreas de sidebar do tema ou widgets que não suportam blocos, use a abordagem de [Shortcode](#uso-de-shortcode). + +--- + +## Uso de Shortcode + +Use o shortcode `[tsparticles]` no Editor Clássico, blocos HTML personalizados ou diretamente em arquivos de template PHP para incorporar fundos de partículas em qualquer lugar do seu site. + +### Shortcode Básico + +``` +[tsparticles] +``` + +Isso renderiza a configuração padrão de partículas (círculos flutuantes simples em fundo escuro). + +### Shortcode com Opções + +Passe configuração JSON diretamente no shortcode usando o atributo `options`: + +``` +[tsparticles options='{"particles":{"number":{"value":50},"color":{"value":"#ff0000"},"shape":{"type":"circle"},"opacity":{"value":0.5},"size":{"value":{"min":1,"max":3}},"move":{"enable":true,"speed":1,"outModes":{"default":"bounce"}}},"background":{"color":"#1a1a2e"}}'] +``` + +### Shortcode em Templates PHP + +```php +// No header.php ou footer.php do seu tema +echo do_shortcode('[tsparticles]'); +``` + +Ou com opções personalizadas: + +```php +$options = [ + 'particles' => [ + 'number' => ['value' => 80], + 'color' => ['value' => '#00d4ff'], + 'shape' => ['type' => 'circle'], + 'links' => [ + 'enable' => true, + 'distance' => 150, + 'color' => '#00d4ff', + 'opacity' => 0.3, + ], + 'move' => [ + 'enable' => true, + 'speed' => 1.5, + 'outModes' => ['default' => 'bounce'], + ], + ], + 'background' => ['color' => '#0d1117'], +]; + +echo do_shortcode('[tsparticles options=\'' . wp_json_encode($options) . '\']'); +``` + +--- + +## Configuração via Filtro PHP + +O plugin expõe um filtro `tsparticles_options` que permite sobrescrever ou estender a configuração das partículas a partir do arquivo `functions.php` do seu tema ou de um plugin personalizado. Esta é a abordagem recomendada para desenvolvedores porque mantém a configuração em PHP e evita JSON inline. + +### Filtro Básico + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + $options['background'] = ['color' => '#0d1117']; + $options['particles']['number']['value'] = 100; + $options['particles']['color']['value'] = '#00d4ff'; + $options['particles']['shape']['type'] = 'circle'; + $options['particles']['opacity']['value'] = 0.6; + $options['particles']['size']['value'] = ['min' => 2, 'max' => 5]; + $options['particles']['links']['enable'] = true; + $options['particles']['links']['distance'] = 150; + $options['particles']['links']['color'] = '#00d4ff'; + $options['particles']['links']['opacity'] = 0.3; + $options['particles']['move']['enable'] = true; + $options['particles']['move']['speed'] = 1.5; + $options['particles']['move']['outModes']['default'] = 'bounce'; + return $options; +}); +``` + +Este filtro é executado antes do shortcode ou bloco renderizar, então qualquer instância de tsParticles na página recebe a configuração personalizada. + +--- + +## Configuração Personalizada via Filtro + +Aqui está uma configuração personalizada completa que demonstra todo o poder do filtro — incluindo interatividade, múltiplos tipos de forma e suporte a temas. + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + + // Fundo tela cheia + $options['fullScreen'] = [ + 'enable' => true, + 'zIndex' => -1, + ]; + + $options['fpsLimit'] = 60; + + // Configurações das partículas + $options['particles'] = [ + 'number' => [ + 'value' => 60, + 'density' => ['enable' => true, 'width' => 800, 'height' => 800], + ], + 'color' => [ + 'value' => ['#ff6b6b', '#feca57', '#48dbfb', '#ff9ff3', '#54a0ff'], + ], + 'shape' => [ + 'type' => ['circle', 'triangle', 'polygon'], + 'options' => [ + 'polygon' => ['sides' => 6], + ], + ], + 'opacity' => [ + 'value' => ['min' => 0.4, 'max' => 0.8], + ], + 'size' => [ + 'value' => ['min' => 3, 'max' => 8], + ], + 'links' => [ + 'enable' => true, + 'distance' => 200, + 'color' => '#ffffff', + 'opacity' => 0.15, + 'width' => 1, + ], + 'move' => [ + 'enable' => true, + 'speed' => 2, + 'direction' => 'none', + 'random' => true, + 'straight' => false, + 'outModes' => ['default' => 'out'], + ], + ]; + + // Interatividade + $options['interactivity'] = [ + 'events' => [ + 'onHover' => ['enable' => true, 'mode' => 'attract'], + 'onClick' => ['enable' => true, 'mode' => 'repulse'], + ], + 'modes' => [ + 'attract' => ['distance' => 200, 'duration' => 0.4, 'factor' => 1], + 'repulse' => ['distance' => 200, 'duration' => 0.4], + ], + ]; + + // Fundo + $options['background'] = [ + 'color' => '#0f0f23', + ]; + + // Suporte a tema — alternância para modo claro + $options['themes'] = [ + [ + 'name' => 'light', + 'default' => ['value' => false], + 'options' => [ + 'background' => ['color' => '#f0f0f5'], + 'particles' => [ + 'color' => ['value' => ['#e74c3c', '#2ecc71', '#3498db', '#f1c40f']], + 'links' => ['color' => '#333333', 'opacity' => 0.2], + ], + ], + ], + ]; + + return $options; +}); +``` + +--- + +## Integração com Temas + +Para tornar o tsParticles um fundo persistente em todo o seu tema WordPress, adicione o shortcode ou uma chamada PHP direta ao `header.php` ou `footer.php` do seu tema. + +### Fundo no Cabeçalho + +```php + + +
+ +
+ +``` + +### Estilos de Fundo Tela Cheia + +Adicione o seguinte CSS ao `style.css` do seu tema ou via `wp_add_inline_style`: + +```css +#tsparticles-background { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + z-index: -1; + pointer-events: none; +} + +/* Garantir que o conteúdo apareça acima das partículas */ +.site-content { + position: relative; + z-index: 1; +} +``` + +### Carregamento Condicional + +Para carregar tsParticles apenas em páginas específicas: + +```php +// Em functions.php — enfileirar apenas na página inicial +add_action('wp', function () { + if (is_front_page()) { + add_filter('tsparticles_options', function (array $options): array { + $options['particles']['number']['value'] = 120; + $options['particles']['color']['value'] = '#ffffff'; + $options['particles']['move']['speed'] = 0.8; + $options['background']['color'] = '#1a1a2e'; + return $options; + }); + } +}); +``` + +Combine isso com a colocação do bloco ou shortcode para um fundo de partículas eficiente e específico por página. + +--- + +Você tem agora tudo que precisa para integrar tsParticles em um site WordPress. Quer prefira o editor de blocos, shortcodes ou controle total via PHP, cada abordagem fornece um fundo de partículas único com esforço mínimo. diff --git a/websites/website/docs/ru/guide/bundles-all.md b/websites/website/docs/ru/guide/bundles-all.md index 5d6e91820f6..442ae2b0c10 100644 --- a/websites/website/docs/ru/guide/bundles-all.md +++ b/websites/website/docs/ru/guide/bundles-all.md @@ -1,21 +1,42 @@ # Bundle: All -`@tsparticles/all` загружает все официальные возможности и удобен для быстрого прототипирования. +`@tsparticles/all` загружает **всё** из репозитория tsParticles: каждую форму, взаимодействие, обновление, эффект, путь, easing, плагин и экспорт. Это самый большой bundle, предназначенный для прототипирования и демонстраций. -## Когда выбирать All +## Включённые возможности -- Нужны все возможности сразу. -- Вы быстро исследуете варианты. -- Размер bundle менее важен, чем скорость setup. +Наследует всё из `tsparticles` (full) плюс: + +**Все формы:** arrow, cards, cog, heart, infinity, matrix, path, ribbon, rounded-polygon, rounded-rect, spiral, squircle + +**Все внешние взаимодействия:** cannon, light, particle, pop, particles-repulse + +**Все эффекты:** bubble, filter, particles, shadow, trail + +**Все генераторы путей:** branches, brownian, curl-noise, curves, fractal-noise, grid, levy, perlin-noise, polygon, random, simplex-noise, spiral, svg, zig-zag + +**Все easing:** back, bounce, circ, cubic, elastic, expo, gaussian, linear, quad, quart, quint, sigmoid, sine, smoothstep + +**Все цветовые плагины:** HEX, HSL, RGB, HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH + +**Все плагины:** абсорберы, background-mask, canvas-mask, эмиттеры (все формы), easing (все), export-image, export-json, export-video, infection, manual-particles, motion, poisson-disc, polygon-mask, responsive, звуки, темы, trail, zoom + +**Все обновления:** destroy, gradient, life, opacity, orbit, out-modes, paint, roll, rotate, size, tilt, twinkle, wobble + +## Когда использовать + +- Быстрое прототипирование для изучения возможностей +- Демо и показы +- Среды разработки, где размер не имеет значения +- **Не рекомендуется для production** — предпочитайте более целевые bundle ## Установка +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/all ``` -## Пример настройки - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadAll } from "@tsparticles/all"; @@ -25,20 +46,48 @@ await loadAll(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { number: { value: 100 }, + shape: { type: "heart" }, move: { enable: true, speed: 2 }, }, }, }); ``` +### CDN (теги script) + +```html + + + +``` + +## Разница между `tsparticles` и `@tsparticles/all` + +См. таблицу сравнения на странице [bundles-full](/ru/guide/bundles-full) для детального разбора. + ## Частые ошибки -- Использовать в production, когда лучше подошел бы более узкий bundle. -- Вызывать `tsParticles.load(...)` до `loadAll(...)`. +- Использование в production — предпочитайте `@tsparticles/slim` или `tsparticles` для меньших bundle. +- Вызов `tsParticles.load()` до `loadAll(tsParticles)`. -## Связанные страницы +## См. также -- Обзор: [`/guide/bundles`](/ru/guide/bundles) -- Матрица установки: [`/guide/installation`](/ru/guide/installation) +- [Обзор bundle](/ru/guide/bundles) +- [Руководство по установке](/ru/guide/installation) diff --git a/websites/website/docs/ru/guide/bundles-basic.md b/websites/website/docs/ru/guide/bundles-basic.md index caaf6ad9fe2..fd776b190eb 100644 --- a/websites/website/docs/ru/guide/bundles-basic.md +++ b/websites/website/docs/ru/guide/bundles-basic.md @@ -1,21 +1,46 @@ # Bundle: Basic -`@tsparticles/basic` подходит для максимально легких setup с минимальным runtime. +`@tsparticles/basic` — самый лёгкий bundle. Включает только самое необходимое: круги, которые двигаются с анимируемой прозрачностью и размером. -## Когда выбирать Basic +## Включённые возможности -- Размер bundle - главный приоритет. -- Нужны только базовые эффекты. -- Расширенные plugins не требуются. +**Формы:** круг + +**Обновления:** + +- paint (цвет) +- прозрачность +- out-modes (поведение при выходе за экран) +- размер + +**Плагины:** + +- move +- blend (смешивание цветов) +- HEX, HSL, RGB цветовые плагины + +**Не включено:** + +- Взаимодействия мыши/тача +- Связи частиц +- Другие формы (квадраты, звёзды, изображения, полигоны и т.д.) +- Эмиттеры, абсорберы, звуки +- Вращение, жизнь, roll, tilt, wobble + +## Когда использовать + +- Размер bundle — ваш главный приоритет +- Вам нужны только движущиеся точки +- Не нужны взаимодействия или сложные формы ## Установка +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/basic ``` -## Пример настройки - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadBasic } from "@tsparticles/basic"; @@ -25,20 +50,48 @@ await loadBasic(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#ffffff" }, particles: { number: { value: 50 }, - move: { enable: true, speed: 1.5 }, + color: { value: ["#5bc0eb", "#fde74c", "#9bc53d"] }, + size: { + value: { min: 300, max: 400 }, + animation: { enable: true, speed: 100 }, + }, + move: { enable: true, speed: 10 }, }, }, }); ``` +### CDN (теги script) + +```html + + + +``` + ## Частые ошибки -- Ожидать функции из plugins, которые не входят в basic. -- Вызывать `tsParticles.load(...)` до `loadBasic(...)`. +- Ожидание функций, не входящих в basic (например, `links`, взаимодействия мыши) — для них нужны более полные bundle. +- Вызов `tsParticles.load()` до `loadBasic(tsParticles)` — формы и обновления ещё не зарегистрированы. +- Установка только `@tsparticles/engine` без bundle — движок сам по себе ничего не рисует. -## Связанные страницы +## См. также -- Обзор: [`/guide/bundles`](/ru/guide/bundles) -- Матрица установки: [`/guide/installation`](/ru/guide/installation) +- [Обзор bundle](/ru/guide/bundles) +- [Руководство по установке](/ru/guide/installation) diff --git a/websites/website/docs/ru/guide/bundles-confetti.md b/websites/website/docs/ru/guide/bundles-confetti.md index e5037fe2616..6ecca24fc30 100644 --- a/websites/website/docs/ru/guide/bundles-confetti.md +++ b/websites/website/docs/ru/guide/bundles-confetti.md @@ -1,42 +1,83 @@ # Bundle: Confetti -`@tsparticles/confetti` предоставляет специализированное API для эффектов конфетти с минимальным setup. +`@tsparticles/confetti` предоставляет упрощённое API для создания эффектов конфетти одним вызовом функции. Не требуется напрямую взаимодействовать с `tsParticles`. -## Когда выбирать Confetti +## Включённые возможности -- Нужны праздничные эффекты в один вызов. -- Не хотите вручную подключать engine. -- Предпочитаете компактный API для UI-событий. +**Формы:** круг, сердце, карты (французские масти: черви, бубны, трефы, пики), эмодзи, изображения, полигон, квадрат, звезда + +**Внутренние плагины:** эмиттеры, motion (учитывает предпочтение пользователя по уменьшению движения) + +**Обновления:** жизнь, roll, вращение, tilt, wobble + +**API:** `confetti(options)` или `confetti(идентификаторCanvas, options)` + +## Когда использовать + +- Кнопка "Поздравляем!" или "С днём рождения!" +- Быстрый праздничный эффект +- Вы не хотите настраивать движок вручную ## Установка +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/confetti ``` -## Пример настройки - ```ts import { confetti } from "@tsparticles/confetti"; +// Базовый эффект await confetti({ - count: 80, - spread: 60, + particleCount: 100, + spread: 70, + origin: { x: 0.5, y: 0.5 }, }); -await confetti("canvas-id", { - count: 50, +// На конкретном canvas +await confetti("my-canvas-id", { + particleCount: 50, angle: 90, spread: 45, + colors: ["#ff0000", "#00ff00", "#0000ff"], }); ``` +### CDN (тег script) + +```html + + +``` + +### Основные параметры + +| Параметр | Тип | По умолчанию | Описание | +| --------------- | -------- | ------------ | --------------------------------------------------- | +| `particleCount` | number | 50 | Количество частиц конфетти | +| `spread` | number | 60 | Угол разброса (градусы) | +| `angle` | number | 90 | Направление (градусы, 90 = вниз) | +| `startVelocity` | number | 30 | Начальная скорость | +| `colors` | string[] | — | Цвета конфетти | +| `origin` | { x, y } | { 0.5, 0.5 } | Точка начала (0-1) | +| `drift` | number | 0 | Горизонтальный снос | +| `shapes` | string[] | — | Формы: "circle", "heart", "square", "star", "cards" | + ## Частые ошибки -- Считать, что `tsParticles` экспортируется из `@tsparticles/confetti`. -- Непреднамеренно использовать один и тот же canvas id повторно. +- Думать, что `tsParticles` экспортируется из `@tsparticles/confetti` — это не так. +- Непреднамеренное повторное использование одного и того же ID canvas. +- Вызов `confetti` в цикле без управления производительностью — используйте разумный интервал или остановите анимацию по завершении. -## Связанные страницы +## См. также -- Обзор: [`/guide/bundles`](/ru/guide/bundles) -- Bundle playground: [`/playground/bundles`](/ru/playground/bundles) +- [Обзор bundle](/ru/guide/bundles) +- [Bundle фейерверков](/ru/guide/bundles-fireworks) diff --git a/websites/website/docs/ru/guide/bundles-fireworks.md b/websites/website/docs/ru/guide/bundles-fireworks.md index 57569b11a82..e0340cbb842 100644 --- a/websites/website/docs/ru/guide/bundles-fireworks.md +++ b/websites/website/docs/ru/guide/bundles-fireworks.md @@ -1,44 +1,81 @@ # Bundle: Fireworks -`@tsparticles/fireworks` предоставляет специализированное API для эффектов фейерверка с минимальным setup. +`@tsparticles/fireworks` предоставляет упрощённое API для создания эффектов фейерверков одним вызовом функции. Поддерживает звуки, пользовательские цвета и управление экземпляром (пауза/воспроизведение). -## Когда выбирать Fireworks +## Включённые возможности -- Нужны fireworks-анимации в один вызов. -- Не нужен прямой wiring движка. -- Нужен компактный API для праздничных сценариев. +**Формы:** линия, круг (из basic) + +**Внутренние плагины:** эмиттеры, emitters-shape-square, blend (смешивание), звуки + +**Обновления:** destroy, жизнь, paint, вращение + +**API:** `fireworks(options)` — возвращает управляемый экземпляр + +## Когда использовать + +- Эффект для Нового года или праздника +- Праздничный интерфейс +- Вы не хотите настраивать движок вручную ## Установка +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/fireworks ``` -## Пример настройки - ```ts import { fireworks } from "@tsparticles/fireworks"; +// Базовый эффект const instance = await fireworks({ - colors: ["#ffffff", "#ff0000"], - sounds: false, + colors: ["#ffffff", "#ff0000", "#00ff00", "#0000ff"], + sounds: true, }); +// Управление экземпляром instance?.pause(); instance?.play(); -await fireworks("canvas-id", { +// На конкретном canvas +await fireworks("my-canvas", { rate: 3, speed: { min: 10, max: 25 }, + sounds: false, }); ``` +### CDN (тег script) + +```html + + +``` + +### Основные параметры + +| Параметр | Тип | По умолчанию | Описание | +| ------------ | ------------ | ------------ | ---------------------------- | +| `colors` | string[] | — | Цвета взрывов | +| `rate` | number | — | Фейерверков в секунду | +| `speed` | { min, max } | — | Скорость частиц | +| `sounds` | boolean | true | Включить звуковые эффекты | +| `gravity` | number | — | Гравитация (по умолчанию: 0) | +| `opacity` | number | — | Прозрачность (0-1) | +| `brightness` | { min, max } | — | Яркость взрыва | + ## Частые ошибки -- Считать, что `tsParticles` экспортируется из `@tsparticles/fireworks`. -- Вызывать `fireworks(...)` много раз без управления возвращенной instance. +- Думать, что `tsParticles` экспортируется из `@tsparticles/fireworks` — это не так. +- Вызов `fireworks()` в цикле без управления экземпляром — эффект уже непрерывный. +- Остановка экземпляра при уходе со страницы не производится — вызывайте `instance?.pause()` или `instance?.stop()`. -## Связанные страницы +## См. также -- Обзор: [`/guide/bundles`](/ru/guide/bundles) -- Bundle playground: [`/playground/bundles`](/ru/playground/bundles) +- [Обзор bundle](/ru/guide/bundles) +- [Bundle конфетти](/ru/guide/bundles-confetti) diff --git a/websites/website/docs/ru/guide/bundles-full.md b/websites/website/docs/ru/guide/bundles-full.md index 45af40ae0c5..f1b70e61911 100644 --- a/websites/website/docs/ru/guide/bundles-full.md +++ b/websites/website/docs/ru/guide/bundles-full.md @@ -1,21 +1,48 @@ # Bundle: tsparticles (Full) -`tsparticles` - это full-bundle, включающий широкий набор официальных возможностей с одним loader. +`tsparticles` (npm: `tsparticles`, загрузчик: `loadFull`) — официальный полный bundle. Включает всё из Slim плюс эмиттеры, абсорберы, текстовые формы и продвинутые анимации (wobble, roll, tilt, twinkle, destroy). -## Когда выбирать tsparticles (Full) +## Включённые возможности -- Нужны многие официальные возможности без ручного выбора plugins. -- Нужна полная база, готовая к production, перед тонкой настройкой. -- Вы предпочитаете контроль engine через API `tsParticles`. +Наследует всё из `@tsparticles/slim` плюс: + +**Дополнительные формы:** текст (с пользовательскими шрифтами) + +**Дополнительные внешние взаимодействия:** + +- drag (перетаскивание частиц мышью) +- trail (след частиц за мышью) + +**Дополнительные обновления:** + +- destroy (анимация уничтожения частиц) +- roll (перекатывание) +- tilt (3D наклон) +- twinkle (мерцание) +- wobble (колебание) + +**Плагины:** + +- абсорберы (чёрные дыры, втягивающие частицы) +- эмиттеры (непрерывные источники частиц) +- emitters-shape-circle, emitters-shape-square (формы эмиттеров) + +## Когда использовать + +- Нужны эмиттеры (частицы, появляющиеся непрерывно) +- Нужны абсорберы (частицы, втягиваемые внутрь) +- Нужны текстовые формы с пользовательскими шрифтами +- Нужны продвинутые анимации (wobble, tilt, roll, twinkle) +- Хорошая промежуточная ступень перед переходом на отдельные плагины ## Установка +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine tsparticles ``` -## Пример настройки - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadFull } from "tsparticles"; @@ -25,20 +52,65 @@ await loadFull(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { - number: { value: 100 }, - move: { enable: true, speed: 2 }, + number: { value: 50 }, + shape: { type: "text", options: { text: ["🔥", "✨", "⭐"] } }, + size: { value: 24 }, + move: { enable: true, speed: 1 }, + wobble: { enable: true, distance: 10 }, + }, + emitters: { + direction: "top", + rate: { quantity: 2, delay: 0.3 }, }, }, }); ``` +### CDN (теги script) + +```html + + + +``` + +## Разница между `tsparticles` и `@tsparticles/all` + +| Аспект | `tsparticles` (full) | `@tsparticles/all` | +| ---------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| Размер | Умеренный | Очень большой | +| Формы | круг, квадрат, звезда, полигон, линия, изображение, эмодзи, текст | Все формы (сердце, карты, стрелка, спираль, cog, скруглённый прямоугольник и т.д.) | +| Взаимодействия | Slim + drag + trail | Все (cannon, light, pop, particle, repulse) | +| Пути | Только easing Quad | 14 генераторов путей | +| Эффекты | Нет | 5 эффектов (bubble, filter, shadow и т.д.) | +| Экспорты | Нет | Изображение, JSON, Видео | +| Дополнительные плагины | абсорберы, эмиттеры | Все (звуки, темы, trail, zoom, polygon-mask, canvas-mask, background-mask и т.д.) | +| Easing | Quad | 15 easing'ов | + ## Частые ошибки -- Вызывать `tsParticles.load(...)` до `loadFull(...)`. -- Считать, что это тот же пакет, что и `@tsparticles/all` (это разные bundles). +- Путать `tsparticles` с `@tsparticles/all` — это разные пакеты. +- Вызов `tsParticles.load()` до `loadFull(tsParticles)`. +- Пакет npm называется `tsparticles` (не `@tsparticles/full`), загрузчик — `loadFull`. -## Связанные страницы +## См. также -- Обзор: [`/guide/bundles`](/ru/guide/bundles) -- Матрица установки: [`/guide/installation`](/ru/guide/installation) +- [Обзор bundle](/ru/guide/bundles) +- [Руководство по установке](/ru/guide/installation) diff --git a/websites/website/docs/ru/guide/bundles-particles.md b/websites/website/docs/ru/guide/bundles-particles.md index f36f7dbda89..f0720a59c81 100644 --- a/websites/website/docs/ru/guide/bundles-particles.md +++ b/websites/website/docs/ru/guide/bundles-particles.md @@ -1,42 +1,98 @@ # Bundle: Particles -`@tsparticles/particles` предоставляет специализированное API для простых particle backgrounds. +`@tsparticles/particles` предоставляет упрощённое API для создания интерактивных фонов из частиц. Более богатая альтернатива `@tsparticles/basic` с выделенным API вместо ручной настройки движка. -## Когда выбирать Particles +## Включённые возможности -- Нужен быстрый API для фона с частицами. -- Не хотите вручную настраивать engine/plugins. -- Нужен компактный API в стиле app. +**Формы:** круг (из basic) + +**Внутренние плагины:** interactivity (связи, коллизии) + +**Взаимодействия:** связи (links) — соединения частиц, коллизии + +**API:** `particles(options)` или `particles(идентификаторCanvas, options)` + +## Когда использовать + +- Фон из частиц для веб-сайта +- Фон со связями частиц (эффект в стиле узлов) +- Вы не хотите настраивать движок вручную ## Установка +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/particles ``` -## Пример настройки - ```ts import { particles } from "@tsparticles/particles"; +// Фон со связями await particles({ count: 120, links: true, - linksColor: "#0ff", + color: "#ffffff", + linksColor: "#00d8ff", + radius: 3, + speed: 2, + opacity: 0.8, }); -await particles("canvas-id", { +// На конкретном canvas +await particles("my-canvas", { count: 80, shape: ["circle", "square"], + links: true, }); + +// С пользовательскими цветами +await particles({ + count: 100, + color: ["#ff6b6b", "#4ecdc4", "#45b7d1"], + links: false, +}); +``` + +### CDN (тег script) + +```html + + ``` +### Основные параметры + +| Параметр | Тип | По умолчанию | Описание | +| ------------ | ------------------ | ------------ | ------------------ | +| `count` | number | 50 | Количество частиц | +| `radius` | number | 3 | Радиус частицы | +| `speed` | number | 2 | Скорость движения | +| `opacity` | number | 0.8 | Прозрачность (0-1) | +| `color` | string \| string[] | "#ffffff" | Цвет(а) частиц | +| `links` | boolean | false | Показывать связи | +| `linksColor` | string | "#ffffff" | Цвет связей | +| `linksWidth` | number | 1 | Толщина связей | +| `shape` | string[] | ["circle"] | Формы частиц | + ## Частые ошибки -- Считать, что `tsParticles` экспортируется из `@tsparticles/particles`. -- Непреднамеренно использовать один и тот же canvas id повторно. +- Думать, что `tsParticles` экспортируется из `@tsparticles/particles` — это не так. +- Непреднамеренное повторное использование одного и того же ID canvas. +- Ожидание продвинутых форм (звёзды, полигоны) — bundle частиц основан на basic и использует только круги. -## Связанные страницы +## См. также -- Обзор: [`/guide/bundles`](/ru/guide/bundles) -- Bundle playground: [`/playground/bundles`](/ru/playground/bundles) +- [Обзор bundle](/ru/guide/bundles) +- [Начало работы](/ru/guide/getting-started) diff --git a/websites/website/docs/ru/guide/bundles-slim.md b/websites/website/docs/ru/guide/bundles-slim.md index b7848b4d8dd..366f34c37c1 100644 --- a/websites/website/docs/ru/guide/bundles-slim.md +++ b/websites/website/docs/ru/guide/bundles-slim.md @@ -1,21 +1,61 @@ # Bundle: Slim -`@tsparticles/slim` - рекомендуемый выбор по умолчанию для большинства проектов. +`@tsparticles/slim` — рекомендуемый bundle для большинства проектов. Включает всё необходимое для современных анимаций частиц с взаимодействием мыши, множеством форм и связями частиц. -## Когда выбирать Slim +## Включённые возможности -- Нужен хороший баланс между размером и возможностями. -- Вы используете API движка `tsParticles` напрямую. -- Нужны базовые формы/интеракции без загрузки всего набора. +Наследует всё из `@tsparticles/basic` плюс: + +**Формы:** круг, квадрат, звезда, полигон, линия, изображение, эмодзи + +**Внешние взаимодействия (мышь/тач):** + +- attract +- bounce +- bubble +- connect +- destroy +- grab +- parallax +- pause +- push +- remove +- repulse +- slow + +**Взаимодействия частиц:** + +- attract +- коллизии +- связи (links) — соединения частиц + +**Дополнительные обновления:** + +- жизнь (lifecycle) +- вращение + +**Плагины:** + +- interactivity +- easing-quad +- HEX, HSL, RGB цветовые плагины + +## Когда использовать + +- Рекомендуемая отправная точка для большинства проектов +- Нужны несколько форм (круги, звёзды, полигоны, изображения) +- Нужны взаимодействия мыши (клик, наведение, bubble, repulse) +- Нужны связи частиц +- Хороший баланс между размером bundle и функциями ## Установка +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/slim ``` -## Пример настройки - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; @@ -25,21 +65,47 @@ await loadSlim(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#0b1020" }, particles: { number: { value: 80 }, + links: { enable: true, distance: 150 }, move: { enable: true, speed: 2 }, - links: { enable: true }, + shape: { type: ["circle", "star", "square"] }, }, }, }); ``` +### CDN (теги script) + +```html + + + +``` + ## Частые ошибки -- Вызывать `tsParticles.load(...)` до `loadSlim(...)`. -- Смешивать разные версии engine и plugins. +- Вызов `tsParticles.load()` до `loadSlim(tsParticles)`. +- Смешивание разных версий engine и bundle — держите их синхронизированными. +- Ожидание функций из более полных bundle (эмиттеры, абсорберы, текст, wobble) — нужен `tsparticles` (full) или отдельные плагины. -## Связанные страницы +## См. также -- Обзор: [`/guide/bundles`](/ru/guide/bundles) -- Матрица установки: [`/guide/installation`](/ru/guide/installation) +- [Обзор bundle](/ru/guide/bundles) +- [Руководство по установке](/ru/guide/installation) diff --git a/websites/website/docs/ru/guide/bundles.md b/websites/website/docs/ru/guide/bundles.md index 09db8020bcd..f4ff8c65de8 100644 --- a/websites/website/docs/ru/guide/bundles.md +++ b/websites/website/docs/ru/guide/bundles.md @@ -1,104 +1,184 @@ # Руководство по bundle -Эта страница поможет выбрать подходящий bundle `tsParticles` и быстро его настроить. - -## Сравнение пакетов - -| Пакет | Лучше всего подходит для | Стиль настройки | -| ------------------------ | -------------------------------------------------------- | ---------------------------------------------- | -| `@tsparticles/basic` | Очень легкие конфигурации | `tsParticles` + `await loadBasic(tsParticles)` | -| `@tsparticles/slim` | Большинство сайтов/приложений | `tsParticles` + `await loadSlim(tsParticles)` | -| `tsparticles` | Полный набор официальных возможностей с контролем engine | `tsParticles` + `await loadFull(tsParticles)` | -| `@tsparticles/all` | Все возможности, быстрое прототипирование | `tsParticles` + `await loadAll(tsParticles)` | -| `@tsparticles/confetti` | Эффекты конфетти в один вызов | `await confetti(options)` | -| `@tsparticles/fireworks` | Эффекты фейерверков в один вызов | `await fireworks(options)` | -| `@tsparticles/particles` | Простое API для фоновых частиц | `await particles(options)` | -| `@tsparticles/ribbons` | Эффекты ribbons в один вызов | `await ribbons(options)` | - -## Руководства по bundle - -- Basic: [`/guide/bundles-basic`](/ru/guide/bundles-basic) -- Slim: [`/guide/bundles-slim`](/ru/guide/bundles-slim) -- tsparticles (Full): [`/guide/bundles-full`](/ru/guide/bundles-full) -- All: [`/guide/bundles-all`](/ru/guide/bundles-all) -- Confetti: [`/guide/bundles-confetti`](/ru/guide/bundles-confetti) -- Fireworks: [`/guide/bundles-fireworks`](/ru/guide/bundles-fireworks) -- Particles: [`/guide/bundles-particles`](/ru/guide/bundles-particles) -- Ribbons (демо + документация): [`/demos/recipes/ribbons`](/ru/demos/recipes/ribbons) · - -## Установка - -Установите вариант пакетов под ваш сценарий. - -```bash -pnpm add @tsparticles/engine @tsparticles/basic -pnpm add @tsparticles/engine @tsparticles/slim -pnpm add @tsparticles/engine tsparticles -pnpm add @tsparticles/engine @tsparticles/all -pnpm add @tsparticles/confetti -pnpm add @tsparticles/fireworks -pnpm add @tsparticles/particles -pnpm add @tsparticles/ribbons +tsParticles модульна. Пакет `@tsparticles/engine` содержит только ядро; чтобы получить видимые эффекты, необходимо зарегистрировать **формы** (что рисовать), **обновления** (как анимировать), **взаимодействия** (как реагировать на мышь/тач) и **плагины** (дополнительные функции). Всё это делается через **bundle**. + +## Категории bundle + +| Категория | Bundle | API | +| ------------------ | --------------------------------------------------------------------------------------------------- | -------------------------------------------- | +| Движок + загрузчик | `@tsparticles/basic`, `@tsparticles/slim`, `tsparticles`, `@tsparticles/all` | `tsParticles.load({ id, options })` | +| Выделенное API | `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles`, `@tsparticles/ribbons` | `confetti({...})`, `fireworks({...})` и т.д. | + +## Полное сравнение возможностей + +Легенда: ● = включено, ○ = не включено + +| Возможность | basic | slim | full (`tsparticles`) | all | +| --------------------------------------------------------------------------------------------------- | ----- | ---- | -------------------- | ------------------ | +| **Формы** | | | | | +| Круг | ● | ● | ● | ● | +| Квадрат | ○ | ● | ● | ● | +| Звезда | ○ | ● | ● | ● | +| Полигон | ○ | ● | ● | ● | +| Линия | ○ | ● | ● | ● | +| Изображение | ○ | ● | ● | ● | +| Эмодзи | ○ | ● | ● | ● | +| Текст | ○ | ○ | ● | ● | +| Карты (масти) | ○ | ○ | ○ | ● | +| Сердце | ○ | ○ | ○ | ● | +| Стрелка | ○ | ○ | ○ | ● | +| Скруглённый прямоугольник | ○ | ○ | ○ | ● | +| Скруглённый полигон | ○ | ○ | ○ | ● | +| Спираль | ○ | ○ | ○ | ● | +| Squircle | ○ | ○ | ○ | ● | +| Cog | ○ | ○ | ○ | ● | +| Бесконечность | ○ | ○ | ○ | ● | +| Матрица | ○ | ○ | ○ | ● | +| Путь | ○ | ○ | ○ | ● | +| Лента | ○ | ○ | ○ | ● | +| **Внешние взаимодействия (мышь/тач)** | | | | | +| Attract | ○ | ● | ● | ● | +| Bounce | ○ | ● | ● | ● | +| Bubble | ○ | ● | ● | ● | +| Connect | ○ | ● | ● | ● | +| Destroy | ○ | ● | ● | ● | +| Grab | ○ | ● | ● | ● | +| Parallax | ○ | ● | ● | ● | +| Pause | ○ | ● | ● | ● | +| Push | ○ | ● | ● | ● | +| Remove | ○ | ● | ● | ● | +| Repulse | ○ | ● | ● | ● | +| Slow | ○ | ● | ● | ● | +| Drag | ○ | ○ | ● | ● | +| Trail | ○ | ○ | ● | ● | +| Cannon | ○ | ○ | ○ | ● | +| Particle | ○ | ○ | ○ | ● | +| Pop | ○ | ○ | ○ | ● | +| Light | ○ | ○ | ○ | ● | +| **Взаимодействия частиц** | | | | | +| Связи (links) | ○ | ● | ● | ● | +| Коллизии | ○ | ● | ● | ● | +| Attract | ○ | ● | ● | ● | +| Repulse | ○ | ○ | ○ | ● | +| **Обновления (анимации)** | | | | | +| Прозрачность | ● | ● | ● | ● | +| Размер | ● | ● | ● | ● | +| Out modes | ● | ● | ● | ● | +| Paint (цвет) | ● | ● | ● | ● | +| Вращение | ○ | ● | ● | ● | +| Жизнь | ○ | ● | ● | ● | +| Destroy | ○ | ○ | ● | ● | +| Roll | ○ | ○ | ● | ● | +| Tilt | ○ | ○ | ● | ● | +| Twinkle | ○ | ○ | ● | ● | +| Wobble | ○ | ○ | ● | ● | +| Градиент | ○ | ○ | ○ | ● | +| Orbit | ○ | ○ | ○ | ● | +| **Плагины** | | | | | +| Move | ● | ● | ● | ● | +| Blend | ● | ● | ● | ● | +| Эмиттеры | ○ | ○ | ● | ● | +| Абсорберы | ○ | ○ | ● | ● | +| Звуки | ○ | ○ | ○ | ● | +| Motion (предпочтения пользователя) | ○ | ○ | ○ | ● | +| Темы | ○ | ○ | ○ | ● | +| Полигональная маска | ○ | ○ | ○ | ● | +| Canvas-маска | ○ | ○ | ○ | ● | +| Маска фона | ○ | ○ | ○ | ● | +| Экспорт (изображение, json, видео) | ○ | ○ | ○ | ● | +| Ручные частицы | ○ | ○ | ○ | ● | +| Responsive | ○ | ○ | ○ | ● | +| Trail | ○ | ○ | ○ | ● | +| Zoom | ○ | ○ | ○ | ● | +| Poisson disc | ○ | ○ | ○ | ● | +| **Пути** | | | | | +| Любой путь | ○ | ○ | ○ | ● (14 генераторов) | +| **Эффекты** | | | | | +| Bubble, Filter, Shadow и т.д. | ○ | ○ | ○ | ● (5 эффектов) | +| **Easing** | | | | | +| Quad | ○ | ● | ● | ● | +| Back, Bounce, Circ, Cubic, Elastic, Expo, Gaussian, Linear, Quart, Quint, Sigmoid, Sine, Smoothstep | ○ | ○ | ○ | ● | +| **Цветовые плагины** | | | | | +| HEX, HSL, RGB | ● | ● | ● | ● | +| HSV, HWB, LAB, LCH, Named, OKLAB, OKLCH | ○ | ○ | ○ | ● | + +### Bundle с выделенным API + +| Возможность | confetti | fireworks | particles | ribbons | +| ------------------- | ------------------------------------------------------------------ | ---------------------- | ----------------- | ---------------- | +| Формы | круг, сердце, карты, эмодзи, изображение, полигон, квадрат, звезда | линия | (из basic) | лента | +| Взаимодействия | — | — | связи + коллизии | — | +| Специальные плагины | эмиттеры, motion | эмиттеры, звуки, blend | — | эмиттеры, motion | +| Вызов API | `confetti(opts)` | `fireworks(opts)` | `particles(opts)` | `ribbons(opts)` | + +## Руководство по выбору + +```mermaid +flowchart TD + A[Нужно начать быстро?] -->|Да| B[Использовать пресет?] + A -->|Нет| C[Какой размер bundle?] + B -->|Да| D["@tsparticles/configs + @tsparticles/slim"] + B -->|Нет| E["Конфетти? → @tsparticles/confetti"] + B -->|Нет| F["Фейерверки? → @tsparticles/fireworks"] + B -->|Нет| G["Фон-частицы? → @tsparticles/particles"] + B -->|Нет| H["Ленты? → @tsparticles/ribbons"] + C -->|"Минимально (только круги)"| I["@tsparticles/basic"] + C -->|"Средне (формы + взаимодействия)"| J["@tsparticles/slim"] + C -->|"Максимально (все функции)"| K["tsparticles (loadFull)"] + C -->|"Весь репозиторий"| L["@tsparticles/all"] ``` -Нужны CDN-ссылки и другие варианты package manager? - -- См. [`/guide/installation`](/ru/guide/installation). - -## Примеры настройки - -### Bundle с engine + loader (`basic`, `slim`, `full`, `all`) - -```ts -import { tsParticles } from "@tsparticles/engine"; -import { loadSlim } from "@tsparticles/slim"; - -await loadSlim(tsParticles); - -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - number: { value: 80 }, - move: { enable: true, speed: 2 }, - }, - }, -}); +**Правила выбора:** + +1. Большинство проектов начинают с `@tsparticles/slim`. +2. Если размер bundle критичен и нужны только круги: `@tsparticles/basic`. +3. Если нужны эмиттеры, абсорберы, текст, wobble/tilt/roll: `tsparticles` с `loadFull`. +4. Для быстрого прототипирования со всеми функциями: `@tsparticles/all`. +5. Для целевых эффектов (конфетти, фейерверки, фон-частицы, ленты) с минимальной настройкой: bundle с выделенным API. + +## Быстрая установка + +| Bundle | Команда npm | Функция загрузки | CDN URL | +| ------------------------ | ------------------------------------------------- | ------------------------ | -------------------------------------------------------------- | +| `@tsparticles/basic` | `pnpm add @tsparticles/engine @tsparticles/basic` | `loadBasic(tsParticles)` | `@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| `@tsparticles/slim` | `pnpm add @tsparticles/engine @tsparticles/slim` | `loadSlim(tsParticles)` | `@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| `tsparticles` (full) | `pnpm add @tsparticles/engine tsparticles` | `loadFull(tsParticles)` | `tsparticles@4/tsparticles.bundle.min.js` | +| `@tsparticles/all` | `pnpm add @tsparticles/engine @tsparticles/all` | `loadAll(tsParticles)` | `@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| `@tsparticles/confetti` | `pnpm add @tsparticles/confetti` | `confetti(opts)` | `@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| `@tsparticles/fireworks` | `pnpm add @tsparticles/fireworks` | `fireworks(opts)` | `@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| `@tsparticles/particles` | `pnpm add @tsparticles/particles` | `particles(opts)` | `@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| `@tsparticles/ribbons` | `pnpm add @tsparticles/ribbons` | `ribbons(opts)` | `@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | + +**Примечание:** для basic/slim/full/all bundle необходимо вызвать `load*` перед `tsParticles.load()`. CDN-файлы выставляют функцию загрузки глобально, но не вызывают её автоматически. Bundle confetti/fireworks/particles/ribbons имеют самодостаточное API — вызывайте `confetti()`, `fireworks()` и т.д. напрямую. + +CDN-пример для `@tsparticles/slim`: + +```html + + + ``` -Для других пресетов замените только импорт/функцию loader: +CDN-пример для `@tsparticles/confetti`: -- `@tsparticles/basic` -> `loadBasic` -- `tsparticles` -> `loadFull` -- `@tsparticles/all` -> `loadAll` - -### Фокусные API (`confetti`, `fireworks`, `particles`, `ribbons`) - -```ts -import { confetti } from "@tsparticles/confetti"; -import { fireworks } from "@tsparticles/fireworks"; -import { particles } from "@tsparticles/particles"; -import { ribbons } from "@tsparticles/ribbons"; - -await confetti({ count: 80, spread: 60 }); -await fireworks({ sounds: false }); -await particles({ count: 100, links: true }); -await ribbons({ count: 5, spread: 0 }); +```html + + ``` -Эти API удобны, когда нужна быстрая интеграция без ручного подключения большого числа плагинов engine. - -## Практические правила выбора - -1. В большинстве проектов начинайте с `@tsparticles/slim`. -2. Используйте `@tsparticles/basic`, если размер bundle критичен и нужны только простые возможности. -3. Используйте `tsparticles`, когда нужна full-база с широкими возможностями и `loadFull`. -4. Используйте `@tsparticles/all` для прототипирования или когда сразу нужен широкий набор возможностей. -5. Используйте `@tsparticles/confetti`, `@tsparticles/fireworks`, `@tsparticles/particles` или `@tsparticles/ribbons`, когда интерфейсу нужен один специализированный эффект с минимальной настройкой. +См. также [руководство по установке](/ru/guide/installation) для CDN, npm, yarn и подробностей о файлах. ## Связанные страницы -- Фокусные bundles в playground: [`/playground/bundles`](/ru/playground/bundles) -- Стартовый путь: [`/guide/getting-started`](/ru/guide/getting-started) -- Матрица установки: [`/guide/installation`](/ru/guide/installation) -- Обзор wrappers: [`/guide/wrappers`](/ru/guide/wrappers) +- [Начало работы](/ru/guide/getting-started) +- [Руководство по установке](/ru/guide/installation) +- [Каталог пресетов](/ru/demos/presets) +- [Каталог палитр](/ru/demos/palettes) +- [Каталог форм](/ru/demos/shapes) diff --git a/websites/website/docs/ru/guide/color-formats.md b/websites/website/docs/ru/guide/color-formats.md index 5fbc94f3a99..78d1f7742dd 100644 --- a/websites/website/docs/ru/guide/color-formats.md +++ b/websites/website/docs/ru/guide/color-formats.md @@ -1,6 +1,6 @@ # Цветовые форматы -tsParticles поддерживает несколько цветовых форматов в различных параметрах, таких как `background`, `particles.color`, а также в настройках плагина. +tsParticles поддерживает несколько цветовых форматов в различных параметрах, таких как `background`, `particles.paint`, а также в настройках плагина. ## Общие форматы diff --git a/websites/website/docs/ru/guide/getting-started.md b/websites/website/docs/ru/guide/getting-started.md index 41d31c6bc3e..41c526cc0f9 100644 --- a/websites/website/docs/ru/guide/getting-started.md +++ b/websites/website/docs/ru/guide/getting-started.md @@ -1,106 +1,197 @@ # Начало работы -Этот путь — самая быстрая и надежная настройка для `tsParticles` в 2026 году. +tsParticles — это JavaScript/TypeScript библиотека для создания анимаций частиц, конфетти, фейерверков и многого другого. Она работает в любом современном браузере и доступна как в виде npm-пакета, так и через CDN с тегами ` + + + + +
+ + + +``` + +> **Примечание**: даже с CDN-сборками вы ОБЯЗАНЫ вызвать `loadSlim(tsParticles)` (или `loadBasic` / `loadFull` / `loadAll`) перед `tsParticles.load()`. CDN-сборки выставляют функцию загрузки глобально, но не вызывают её автоматически. + +Тот же принцип применим к `@tsparticles/basic` → `loadBasic`, `tsparticles` → `loadFull`, `@tsparticles/all` → `loadAll`. + +### Путь C — Специализированные bundle с собственным API (confetti, fireworks, particles) + +Некоторые bundle имеют свой упрощённый API, без необходимости использовать `tsParticles.load()`: + +```html + + + + + + + + + +``` + +То же самое для `fireworks()`, `particles()`, `ribbons()`. -- `@tsparticles/slim`: здесь должно запускаться большинство приложений. -- `@tsparticles/basic`: меньший набор функций для очень легких настроек. -- `@tsparticles/all`: все включено, проще всего для быстрого прототипирования. +## Какой bundle выбрать? -Если вам нужен специализированный API вместо прямой настройки `tsParticles`: +| Bundle | npm | Когда использовать | +| ------------------------ | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | +| `@tsparticles/basic` | `loadBasic(tsParticles)` | Минимум: круги, движение, прозрачность, размер. Без взаимодействий. | +| `@tsparticles/slim` | `loadSlim(tsParticles)` | **Рекомендуется для большинства проектов.** Добавляет взаимодействия (клик/наведение), связи частиц, изображения, звёзды, полигоны. | +| `tsparticles` | `loadFull(tsParticles)` | Полный официальный набор функций: эмиттеры, абсорберы, текстовые формы, roll, wobble, trail. | +| `@tsparticles/all` | `loadAll(tsParticles)` | **Всё** из репозитория: каждая форма, взаимодействие, эффект, easing, путь, экспорт. Только для прототипирования. | +| `@tsparticles/confetti` | `confetti(options)` | Конфетти одним вызовом функции. Выделенное API. | +| `@tsparticles/fireworks` | `fireworks(options)` | Фейерверки одним вызовом функции. Выделенное API. | +| `@tsparticles/particles` | `particles(options)` | Упрощённый фон из частиц. Выделенное API. | +| `@tsparticles/ribbons` | `ribbons(options)` | Эффект лент. Выделенное API. | -- `@tsparticles/particles`: упрощенный API фона частиц. -- `@tsparticles/confetti`: API конфетти с одним вызовом -- `@tsparticles/fireworks`: API фейерверков с одним вызовом +Подробнее: [`/ru/guide/bundles`](/ru/guide/bundles). -## 5) Используйте пресеты/конфигурации, когда вам нужна скорость +## Использование пресетов -Если вы предпочитаете готовые эффекты: +Пакет `@tsparticles/configs` содержит десятки готовых конфигураций (absorbers, bubbles, snow, stars, gravity, collisions и т.д.). ```bash -pnpm add @tsparticles/configs +pnpm add @tsparticles/engine @tsparticles/slim @tsparticles/configs +``` + +```ts +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import "@tsparticles/configs"; + +await loadSlim(tsParticles); + +await tsParticles.load({ + id: "tsparticles", + options: { preset: "snow" }, +}); ``` -Затем загрузите одну конфигурацию по ключу, например [`demo/vite` app](https://github.com/tsparticles/tsparticles/blob/main/demo/vite/src/main.ts). +С CDN: -Если вы предпочитаете настройки на основе имени пресета, используйте официальный каталог пресетов в [`/demos/presets`](/ru/demos/presets). +```html + + + + +``` -## Быстрая карта документации +## Быстрые ссылки -- Корневые параметры: [`/options/`](/ru/options/) -- Ссылка на обертки: [`/guide/wrappers`](/ru/guide/wrappers) -- Каталог пресетов: [`/demos/presets`](/ru/demos/presets) -- Каталог палитр: [`/demos/palettes`](/ru/demos/palettes) -- Каталог форм: [`/demos/shapes`](/ru/demos/shapes) -- Миграция с particles.js: [`/migrations/particles-js`](/ru/migrations/particles-js) -- Цветовые форматы: [`/guide/color-formats`](/ru/guide/color-formats) -- Жизненный цикл контейнера: [`/guide/container-lifecycle`](/ru/guide/container-lifecycle) -- Плагины и настройка: [`/guide/plugins-customization`](/ru/guide/plugins-customization) +- Документация по опциям: [`/ru/options/`](/ru/options/) +- Руководство по bundle: [`/ru/guide/bundles`](/ru/guide/bundles) +- Каталог пресетов: [`/ru/demos/presets`](/ru/demos/presets) +- Каталог палитр: [`/ru/demos/palettes`](/ru/demos/palettes) +- Каталог форм: [`/ru/demos/shapes`](/ru/demos/shapes) +- Обёртки для фреймворков: [`/ru/guide/wrappers`](/ru/guide/wrappers) +- Цветовые форматы: [`/ru/guide/color-formats`](/ru/guide/color-formats) +- Жизненный цикл контейнера: [`/ru/guide/container-lifecycle`](/ru/guide/container-lifecycle) +- Плагины и настройка: [`/ru/guide/plugins-customization`](/ru/guide/plugins-customization) ## Устранение неполадок -- Пустой экран: убедитесь, что `#tsparticles` существует, прежде чем вызывать `tsParticles.load`. -- Отсутствует функция: вам, вероятно, понадобится другой плагин/пакет (форма, взаимодействие, средство обновления). -- Ошибки типов в параметрах: держите пакеты на одной и той же major/minor версии. +| Проблема | Вероятная причина | Решение | +| ------------------------------------------------------ | ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- | +| Пустой экран, нет частиц | `#tsparticles` не существует в DOM при вызове `tsParticles.load()` | Убедитесь, что DIV существует перед скриптом, или используйте `DOMContentLoaded` | +| Пустой экран, нет частиц | Установлен только `@tsparticles/engine` | Установите также bundle (`@tsparticles/slim`) или плагины — движок сам по себе не имеет форм для отрисовки | +| Ошибка "loadBasic/loadSlim/loadFull is not a function" | Bundle не установлен или неправильный импорт | `pnpm add @tsparticles/slim` и импортируйте `{ loadSlim }` | +| Частицы не двигаются | `move.enable` не установлен в `true` | Добавьте `move: { enable: true, speed: 2 }` | +| Отсутствует функция (например, links, collisions) | Выбранный bundle не включает её | Переключитесь на более богатый bundle (`@tsparticles/slim` или `tsparticles`) или установите конкретный плагин | +| Ошибки типов TypeScript | Версии пакетов не синхронизированы | Держите engine и bundle на одной major/minor версии | diff --git a/websites/website/docs/ru/guide/installation.md b/websites/website/docs/ru/guide/installation.md index eee7ad818a4..eb7178676d9 100644 --- a/websites/website/docs/ru/guide/installation.md +++ b/websites/website/docs/ru/guide/installation.md @@ -1,109 +1,146 @@ # Установка -Эта страница повторяет матрицу установки из основного README проекта `tsParticles`. - -Официальный источник: - ## Выберите свой путь -- **Быстрый старт по умолчанию**: `@tsparticles/engine` + `@tsparticles/slim` -- **Более легкий кастомный runtime**: `@tsparticles/engine` + только нужные plugins -- **Фокусные API**: `@tsparticles/particles`, `@tsparticles/confetti`, `@tsparticles/fireworks` или `@tsparticles/ribbons` -- **Все функции включены**: `@tsparticles/all` - -## Хостинг / CDN - -Используйте одного из этих провайдеров (или размещайте собранные файлы самостоятельно). +| Сценарий | Команда | +| ----------------------------- | ------------------------------------------------- | +| Быстрый старт (рекомендуется) | `pnpm add @tsparticles/engine @tsparticles/slim` | +| Минимальная настройка | `pnpm add @tsparticles/engine @tsparticles/basic` | +| Полный набор функций | `pnpm add @tsparticles/engine tsparticles` | +| Всё из репозитория | `pnpm add @tsparticles/engine @tsparticles/all` | +| Только конфетти | `pnpm add @tsparticles/confetti` | +| Только фейерверки | `pnpm add @tsparticles/fireworks` | +| Фон из частиц | `pnpm add @tsparticles/particles` | +| Эффект лент | `pnpm add @tsparticles/ribbons` | -### jsDelivr +> **Важно**: `@tsparticles/engine` сам по себе ничего не рисует. Вы всегда должны добавить bundle (для загрузки форм и анимаций) или отдельные плагины. См. [руководство по bundle](/ru/guide/bundles). -- -- -- -- -- -- -- -- +## npm -### cdnjs +```bash +# engine + slim (рекомендуется для большинства проектов) +npm install @tsparticles/engine @tsparticles/slim -- +# engine + basic (минимально) +npm install @tsparticles/engine @tsparticles/basic -### unpkg +# engine + full (tsparticles) +npm install @tsparticles/engine tsparticles -- -- -- -- -- -- -- -- +# engine + all +npm install @tsparticles/engine @tsparticles/all -## Установка через package manager +# Bundle с выделенным API (явный engine не требуется) +npm install @tsparticles/confetti +npm install @tsparticles/fireworks +npm install @tsparticles/particles +npm install @tsparticles/ribbons +``` -### npm +## yarn ```bash -npm install @tsparticles/engine +yarn add @tsparticles/engine @tsparticles/slim +# ... тот же принцип для других bundle ``` -### yarn +## pnpm ```bash -yarn add @tsparticles/engine +pnpm add @tsparticles/engine @tsparticles/slim +# ... тот же принцип для других bundle ``` -### pnpm +## CDN (теги script) -```bash -pnpm add @tsparticles/engine -``` +Все пакеты доступны на jsDelivr, unpkg и cdnjs. -## Import и require +### jsDelivr -```ts -const tsParticles = require("@tsparticles/engine"); +| Bundle | URL | +| ---------------------------- | ------------------------------------------------------------------------------------------- | +| Engine | `https://cdn.jsdelivr.net/npm/@tsparticles/engine@4/tsparticles.engine.min.js` | +| Basic | `https://cdn.jsdelivr.net/npm/@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| Slim | `https://cdn.jsdelivr.net/npm/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| Full (`tsparticles`) | `https://cdn.jsdelivr.net/npm/tsparticles@4/tsparticles.bundle.min.js` | +| All | `https://cdn.jsdelivr.net/npm/@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| Confetti | `https://cdn.jsdelivr.net/npm/@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| Fireworks | `https://cdn.jsdelivr.net/npm/@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| Particles | `https://cdn.jsdelivr.net/npm/@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| Ribbons | `https://cdn.jsdelivr.net/npm/@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | +| Совместимость с particles.js | `https://cdn.jsdelivr.net/npm/@tsparticles/pjs@4/tsparticles.pjs.min.js` | -// or +### unpkg -import { tsParticles } from "@tsparticles/engine"; -``` +Та же структура: `https://unpkg.com/{имя-пакета}@{версия}/{имя-файла}` -## Минимальная настройка runtime (`@tsparticles/slim`) +Пример: +`https://unpkg.com/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` + +### cdnjs + +`https://cdnjs.com/libraries/tsparticles` + +## Примеры импорта + +### С бандлером (импорт ES-модуля) ```ts +// Engine + загрузчик bundle import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; await loadSlim(tsParticles); +await tsParticles.load({ id: "tsparticles", options: { ... } }); +``` -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - move: { - enable: true, - }, - number: { - value: 60, - }, - }, - }, -}); +### С CommonJS (require) + +```ts +const { tsParticles } = require("@tsparticles/engine"); +const { loadSlim } = require("@tsparticles/slim"); + +(async () => { + await loadSlim(tsParticles); + await tsParticles.load({ id: "tsparticles", options: { ... } }); +})(); ``` -## Связанные страницы +### С CDN (тег script) + +```html + + + + + + +``` -- [`/guide/getting-started`](/ru/guide/getting-started) -- [`/guide/wrappers`](/ru/guide/wrappers) -- [`/demos/presets`](/ru/demos/presets) -- [`/migrations/particles-js`](/ru/migrations/particles-js) +С bundle с выделенным API: -## Legacy-совместимость +```html + + +``` -Если вы мигрируете старые интеграции particles.js, используйте пакет совместимости: +## Связанные страницы -- npm: -- jsDelivr: +- [Начало работы](/ru/guide/getting-started) +- [Руководство по bundle](/ru/guide/bundles) +- [Обёртки для фреймворков](/ru/guide/wrappers) diff --git a/websites/website/docs/ru/guides/angular.md b/websites/website/docs/ru/guides/angular.md new file mode 100644 index 00000000000..75d8ab2e003 --- /dev/null +++ b/websites/website/docs/ru/guides/angular.md @@ -0,0 +1,631 @@ +--- +title: Интеграция с Angular +description: Пошаговое руководство по интеграции tsParticles в приложения Angular с использованием @tsparticles/angular. +--- + +# Интеграция с Angular + +Пакет `@tsparticles/angular` предоставляет Angular-компоненты, модули и сервисы для tsParticles. Это руководство охватывает традиционный подход с `NgModule`, а также standalone-компоненты Angular 17+. + +--- + +## Установка + +```bash +npm install @tsparticles/angular @tsparticles/engine +``` + +Для полного набора функций установите полную сборку: + +```bash +npm install tsparticles +``` + +Дополнительные пакеты пресетов: + +```bash +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +``` + +--- + +## Базовое использование (NgModule) + +### 1. Импорт модуля + +```typescript +import { NgModule } from "@angular/core"; +import { BrowserModule } from "@angular/platform-browser"; +import { NgParticlesModule } from "@tsparticles/angular"; +import { AppComponent } from "./app.component"; + +@NgModule({ + declarations: [AppComponent], + imports: [BrowserModule, NgParticlesModule], + bootstrap: [AppComponent], +}) +export class AppModule {} +``` + +### 2. Инициализация движка + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d47a1", + }, + fpsLimit: 120, + particles: { + number: { + value: 80, + }, + color: { + value: "#ffffff", + }, + shape: { + type: "circle", + }, + opacity: { + value: 0.5, + }, + size: { + value: { min: 1, max: 5 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Контейнер частиц загружен", container); + } +} +``` + +### 3. Шаблон + +```html + +``` + +--- + +## Детали инициализации движка + +Метод `NgParticlesService.init()` должен быть вызван ровно один раз, обычно в `AppComponent.ngOnInit()`. Он получает колбэк, в котором вы загружаете необходимые плагины/пресеты. + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesService } from "@tsparticles/angular"; +import type { Engine } from "@tsparticles/engine"; + +@Component({ ... }) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + // Загружайте только то, что нужно для меньших сборок + await loadBasic(engine); // базовые формы + движение + await loadEmittersPlugin(engine); // формы эмиттеров + }); + } +} +``` + +Доступные функции загрузки из `tsparticles`: + +| Функция | Описание | +| ------------------- | ----------------------------------------------- | +| `loadFull(engine)` | Все возможности (самая большая сборка) | +| `loadBasic(engine)` | Базовые формы (круг, квадрат, многоугольник...) | +| `loadSlim(engine)` | Большинство функций без редко используемых | +| `loadAll(engine)` | Устаревший псевдоним для `loadFull` | + +--- + +## Эффект конфетти + +```bash +npm install @tsparticles/preset-confetti +``` + +```typescript +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// В колбэке NgParticlesService.init: +await loadConfettiPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "confetti", + background: { + color: "transparent", + }, +}; +``` + +Или используйте удобный компонент ``: + +```typescript +// app.module.ts +import { NgParticlesModule } from "@tsparticles/angular"; + +@NgModule({ + imports: [NgParticlesModule], +}) +export class AppModule {} +``` + +```html + +``` + +--- + +## Эффект фейерверка + +```bash +npm install @tsparticles/preset-fireworks +``` + +```typescript +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; + +// В колбэке NgParticlesService.init: +await loadFireworksPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "fireworks", + background: { + color: "#000000", + }, +}; +``` + +Или используйте компонент ``: + +```html + +``` + +> Избегайте автозапуска фейерверков; привязывайте их к действию пользователя (клик, скролл), чтобы предотвратить нежелательное использование ресурсов. + +--- + +## Пользовательская конфигурация частиц + +Полнофункциональная настройка частиц с интерактивностью: + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-particles", + templateUrl: "./particles.component.html", +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d0d0d", + }, + fpsLimit: 60, + particles: { + number: { + value: 100, + density: { + enable: true, + }, + }, + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + shape: { + type: ["circle", "square", "triangle"], + }, + opacity: { + value: 0.8, + random: true, + anim: { + enable: true, + speed: 1, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + random: true, + anim: { + enable: true, + speed: 4, + size_min: 1, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.3, + width: 1, + triangles: { + enable: true, + color: "#ffffff", + opacity: 0.05, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { + enable: true, + rotateX: 600, + rotateY: 600, + }, + }, + life: { + duration: { + value: 5, + random: true, + }, + count: 0, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: { + enable: true, + }, + }, + modes: { + grab: { + distance: 200, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + detectRetina: true, + }; + + particlesLoaded(container: Container): void { + console.log("Контейнер загружен", container); + } +} +``` + +```html + +``` + +--- + +## События + +Компонент `ngx-particles` emits событие `particlesLoaded`: + +```typescript +import type { Container } from "@tsparticles/engine"; + +// Метод компонента +onParticlesLoaded(container: Container): void { + // Доступ к API контейнера + container.pause(); + container.play(); + container.destroy(); + container.exportImage().then((blob) => { /* ... */ }); +} +``` + +```html + +``` + +Ссылка на контейнер даёт полный программный контроль: пауза, возобновление, уничтожение, экспорт и другое. + +--- + +## Синтаксис шаблона и условный рендеринг + +Используйте структурные директивы Angular для переключения компонента: + +```html + + + +``` + +```typescript +export class AppComponent { + showParticles = true; + // ... +} +``` + +Когда `*ngIf` вычисляется как `false`, компонент уничтожается (включая canvas и все экземпляры частиц). Повторное создание инициализирует всё заново. + +--- + +## Standalone-компоненты (Angular 17+) + +В Angular 17+ вы можете импортировать `NgParticlesModule` напрямую в standalone-компонент: + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesModule, NgParticlesService } from "@tsparticles/angular"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +@Component({ + selector: "app-particles", + standalone: true, + imports: [NgParticlesModule], + template: ` + + `, +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 50 }, + color: { value: "#fff" }, + shape: { type: "circle" }, + move: { enable: true, speed: 2 }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Загружено", container); + } +} +``` + +Обёртка `NgModule` не требуется — просто импортируйте `NgParticlesModule` в массив `imports` компонента. + +--- + +## Полный пример компонента + +### app.component.ts + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + title = "tsParticles Angular Демо"; + + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadSlim(engine); + }); + } + + particlesOptions: ISourceOptions = { + autoPlay: true, + background: { + color: "#1e1e2e", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMask: { + cover: { + color: "#1e1e2e", + }, + enable: false, + }, + fullScreen: { + enable: true, + zIndex: -1, + }, + detectRetina: true, + fpsLimit: 60, + particles: { + color: { + value: "#cdd6f4", + }, + links: { + color: "#cdd6f4", + distance: 150, + enable: true, + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1, + }, + number: { + value: 60, + }, + opacity: { + value: 0.6, + }, + size: { + value: { min: 1, max: 3 }, + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("Частицы загружены", container); + } +} +``` + +### app.component.html + +```html +
+ + +
+

{{ title }}

+

Частицы работают на фоне.

+
+
+``` + +### app.component.css + +```css +:host { + display: block; + width: 100%; + height: 100%; +} +``` + +--- + +## Справочник API + +| Компонент | Селектор | Описание | +| --------- | --------------- | ----------------------------------- | +| Particles | `ngx-particles` | Полноценный компонент частиц | +| Confetti | `ngx-confetti` | Предварительно настроенный конфетти | +| Fireworks | `ngx-fireworks` | Предварительно настроенный салют | + +### Входные параметры `ngx-particles` + +| Параметр | Тип | По умолчанию | Описание | +| --------- | ---------------- | --------------- | -------------------------- | +| `id` | `string` | `"tsparticles"` | ID элемента canvas | +| `options` | `ISourceOptions` | `{}` | Конфигурация частиц | +| `url` | `string` | — | URL удалённой JSON конфиг. | + +### Выходные события `ngx-particles` + +| Событие | Полезные данные | Описание | +| ----------------- | --------------- | ---------------------------------------- | +| `particlesLoaded` | `Container` | Срабатывает при инициализации контейнера | + +--- + +## Устранение неполадок + +- **Пустой / невидимый canvas** — Убедитесь, что родительский элемент имеет заданную высоту (например, `height: 100vh`). Canvas подстраивается под размеры контейнера. +- **`NgParticlesService.init()` вызван несколько раз** — Вызывайте его только один раз, обычно в `AppComponent.ngOnInit()`. Последующие вызовы безопасны, но избыточны. +- **Модуль не найден** — Проверьте, что `@tsparticles/angular` указан в зависимостях `package.json` и что вы импортировали `NgParticlesModule`. +- **`NullInjectorError: No provider for NgParticlesService`** — Необходимо импортировать `NgParticlesModule` (или реэкспортировать его) в модуле, где предоставляется компонент. diff --git a/websites/website/docs/ru/guides/astro.md b/websites/website/docs/ru/guides/astro.md new file mode 100644 index 00000000000..959b516fdef --- /dev/null +++ b/websites/website/docs/ru/guides/astro.md @@ -0,0 +1,384 @@ +# Интеграция с Astro + +Используйте tsParticles на своём сайте Astro с официальным интеграционным пакетом `@tsparticles/astro`. + +## Установка + +Установите интеграцию Astro и ядро tsParticles через ваш менеджер пакетов: + +```bash +npm install @tsparticles/astro tsparticles +``` + +```bash +pnpm add @tsparticles/astro tsparticles +``` + +```bash +yarn add @tsparticles/astro tsparticles +``` + +## Инициализация движка + +tsParticles использует модульную архитектуру. Перед рендерингом частиц необходимо инициализировать движок с нужными вам функциями. Создайте клиентский скрипт (например, `src/scripts/particles-init.ts`) или используйте встроенный ` +``` + +> Проп `id` передаётся базовому контейнеру `
` canvas. Используйте его для стилизации или императивного доступа через `document.getElementById()`. + +## Поддержка TypeScript + +Интеграция поставляется с полными объявлениями TypeScript. Используйте `ISourceOptions` из `@tsparticles/engine` для типизации конфигурации: + +```typescript +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { + value: 50, + density: { enable: true }, + }, + opacity: { value: 0.5 }, + shape: { type: "circle" }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + repulse: { distance: 200 }, + }, + }, +}; +``` + +## Пользовательская конфигурация + +Ниже представлена более детальная конфигурация, которую можно вставить на любую страницу Astro: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + autoPlay: true, + background: { + color: "#0d47a1", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMode: { + enable: true, + zIndex: -1, + }, + fpsLimit: 120, + particles: { + color: { + value: "#ffffff", + animation: { + enable: true, + speed: 20, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + triangles: { + enable: true, + opacity: 0.1, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "out", + attract: { enable: false }, + }, + number: { + value: 80, + density: { + enable: true, + }, + }, + opacity: { + value: 0.5, + animation: { + enable: true, + speed: 1, + sync: false, + }, + }, + shape: { + type: "circle", + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 3, + sync: false, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: true, + }, + modes: { + grab: { + distance: 200, + links: { opacity: 0.5 }, + }, + push: { quantity: 4 }, + }, + }, + detectRetina: true, +}; +--- + + + + +``` + +## Использование пресетов + +Вместо ручного создания конфигурации загрузите пресет во время инициализации движка и укажите его в опциях: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + preset: "stars", + background: { color: "#000000" }, +}; +--- + + + + +``` + +## Интеграция с другими фреймворками + +Поскольку Astro поддерживает UI-фреймворки, такие как React, Vue, Svelte и Solid, вы можете использовать фреймворк-специфичный компонент tsParticles внутри файлов `.astro`: + +### React в Astro + +```astro +--- +import Particles from "@tsparticles/react"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +### Vue в Astro + +```astro +--- +import Particles from "@tsparticles/vue3"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +> Директива `client:load` указывает Astro гидратировать компонент сразу после загрузки страницы. Используйте `client:visible` для отложенной загрузки. + +## Полный пример страницы + +Полная страница Astro с частицами в качестве анимированного фона: + +```astro +--- +import Layout from "../layouts/Layout.astro"; +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + number: { value: 100 }, + color: { value: "#ffffff" }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + size: { + value: { min: 1, max: 4 }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, +}; +--- + + +
+

Добро пожаловать

+

Эта страница имеет фон с частицами на базе tsParticles.

+
+ +
+ + + + +``` + +## Свойства компонента + +| Свойство | Тип | По умолчанию | Описание | +| -------------------- | ---------------- | ------------------------- | ------------------------------------------------ | +| `id` | `string` | `"tsparticles"` | ID DOM-элемента для контейнера | +| `options` | `ISourceOptions` | `{}` | Полный объект конфигурации tsParticles | +| `url` | `string` | — | Загрузить конфигурацию из удалённого JSON URL | +| `particlesClassName` | `string` | `"tsparticles-canvas-el"` | CSS-класс для элемента canvas | +| `container` | `object` | — | Существующий экземпляр `Container` (продвинутое) | diff --git a/websites/website/docs/ru/guides/ember.md b/websites/website/docs/ru/guides/ember.md new file mode 100644 index 00000000000..344d289b1bf --- /dev/null +++ b/websites/website/docs/ru/guides/ember.md @@ -0,0 +1,346 @@ +--- +title: Ember Guide +description: Полное руководство по интеграции tsParticles с приложениями Ember.js. +--- + +# Ember Guide + +## Содержание + +1. [Установка](#установка) +2. [Инициализация движка](#инициализация-движка) +3. [Базовое использование](#базовое-использование) +4. [Пользовательская конфигурация](#пользовательская-конфигурация) +5. [Обработка событий](#обработка-событий) +6. [Условный рендеринг](#условный-рендеринг) +7. [Пример на TypeScript](#пример-на-typescript) + +--- + +## Установка + +Установите Ember-аддон и движок tsParticles через ember-cli: + +```bash +ember install @tsparticles/ember +``` + +Это установит аддон и его зависимость `tsparticles`. При необходимости можно добавить пакеты пресетов: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Инициализация движка + +Аддон экспортирует утилиту `initParticlesEngine`, которую нужно вызвать один раз на уровне приложения. Она принимает асинхронный колбэк, в котором загружаются необходимые функции, пресеты или формы. + +```typescript +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadFull } from "tsparticles"; + +// Вызовите это во время загрузки приложения +if (typeof window !== "undefined") { + void initParticlesEngine(async (engine) => { + await loadFull(engine); + }); +} +``` + +Типичные места для этого вызова — хук `beforeModel` маршрута приложения, конструктор контроллера приложения или инициализатор экземпляра. Синглтон движка инициализируется один раз и используется всеми компонентами `` в вашем приложении. + +--- + +## Базовое использование + +После инициализации движка используйте компонент `` в любом шаблоне. Передайте конфигурацию частиц через аргумент `@options`. + +```hbs +{{! app/templates/application.hbs }} + + +``` + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, + }; +} +``` + +--- + +## Пользовательская конфигурация + +Создайте более насыщенную конфигурацию с интерактивностью, множеством форм и адаптивной плотностью. + +```typescript +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class IndexController extends Controller { + options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, + }; +} +``` + +```hbs + +``` + +--- + +## Обработка событий + +Компонент `` генерирует действие `@particlesLoaded`, когда контейнер завершил инициализацию и первый кадр отрисован. Используйте это для доступа к экземпляру `Container` для программного управления. + +```typescript +import Controller from "@ember/controller"; +import { action } from "@ember/object"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + /* ... */ + }; + + @action + loadedCallback(container: Container) { + console.log("Частицы загружены", container.id); + + // Пример программного управления: + setTimeout(() => { + container.pause(); + console.log("Частицы приостановлены через 5 секунд"); + }, 5000); + } +} +``` + +```hbs + +``` + +Вы также можете использовать шаблон колбэка встроенно с хелпером шаблона, если предпочитаете не определять отдельное действие. + +--- + +## Условный рендеринг + +Используйте хелпер `{{if}}` вместе с `@tracked` свойством для управления рендерингом компонента ``. Это полезно, когда инициализация движка асинхронна и вы хотите избежать рендеринга компонента до готовности движка. + +```typescript +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked engineReady = false; + + options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { enable: true, speed: 1, outModes: { default: "bounce" } }, + }, + background: { color: "#1a1a2e" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } +} +``` + +```hbs +{{#if this.engineReady}} + +{{else}} +

Загрузка частиц...

+{{/if}} +``` + +Декоратор `@tracked` гарантирует автоматический повторный рендеринг шаблона после разрешения промиса. + +--- + +## Пример на TypeScript + +Ниже представлен полный типизированный контроллер приложения Ember, демонстрирующий интеграцию с slim-пресетом, интерактивностью и управлением жизненным циклом. + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked private engineReady = false; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } + + @action + private handleParticlesLoaded(container: Container): void { + this.container = container; + console.log("Частицы загружены в контейнер:", container.id); + } +} +``` + +```hbs +{{! app/templates/application.hbs }} + +{{#if this.engineReady}} +
+

tsParticles + Ember

+ +
+{{else}} +
+

Инициализация движка частиц...

+
+{{/if}} +``` + +--- + +Теперь у вас есть всё необходимое для интеграции tsParticles в приложение Ember.js. Каждый пример самодостаточен и готов к копированию в ваш проект. diff --git a/websites/website/docs/ru/guides/index.md b/websites/website/docs/ru/guides/index.md new file mode 100644 index 00000000000..bbee169e9bc --- /dev/null +++ b/websites/website/docs/ru/guides/index.md @@ -0,0 +1,58 @@ +--- +title: Пошаговые руководства +description: Изучите руководства по интеграции tsParticles в ваш проект для различных фреймворков. +--- + +# Пошаговые руководства + +Добро пожаловать в раздел руководств tsParticles. Создаёте ли вы статический Vanilla JS сайт, одностраничное приложение на React или Vue, или полнофункциональное приложение на Next.js или Nuxt — эти пошаговые руководства проведут вас через установку, базовое использование, продвинутые конфигурации и интерактивные эффекты. + +Каждое руководство самодостаточно и содержит примеры кода для копирования, чтобы вы могли быстро начать работу. + +## Доступные руководства + +| Фреймворк / Обёртка | Пакет | Описание | +| --------------------------------- | ---------------------------------------- | ------------------------------------------------- | +| [Vanilla JS](./vanilla) | `tsparticles` (CDN или npm) | Прямая DOM-интеграция с `tsParticles.load()` | +| [React](./react) | `@tsparticles/react` | Официальная обёртка React с хуками и компонентами | +| [Vue 3](./vue3) | `@tsparticles/vue3` | Официальный плагин Vue 3 с composables | +| [Angular](./angular) | `@tsparticles/angular` | Официальный компонент и модуль Angular | +| [Svelte](./svelte) | `@tsparticles/svelte` | Официальный компонент Svelte | +| [Next.js](./nextjs) | `@tsparticles/react` (с Next.js) | Серверный рендеринг и динамические импорты | +| [Nuxt](./nuxt) | `@tsparticles/vue3` (с Nuxt) | SSR-безопасная интеграция как плагин Nuxt | +| [Solid](./solid) | `@tsparticles/solid` | Официальная обёртка SolidJS | +| [Preact](./preact) | `@tsparticles/preact` | Совместимый компонент Preact | +| [Lit](./lit) | `@tsparticles/lit` | Обёртка веб-компонента Lit | +| [Qwik](./qwik) | `@tsparticles/qwik` | Оптимизированная интеграция для Qwik | +| [jQuery](./jquery) | `@tsparticles/jquery` | Плагин jQuery для легаси-проектов | +| [Astro](./astro) | `@tsparticles/react` (или любая обёртка) | Архитектура Island с клиентскими директивами | +| [Web Components](./webcomponents) | `@tsparticles/webcomponents` | Интеграция через Custom Elements API | +| [Stencil](./stencil) | `@tsparticles/stencil` | Обёртка компонента Stencil | +| [Ember](./ember) | `@tsparticles/ember` | Интеграция аддона Ember | +| [Riot](./riot) | `@tsparticles/riot` | Обёртка Riot.js | +| [Inferno](./inferno) | `@tsparticles/inferno` | Совместимый компонент Inferno | +| [WordPress](./wordpress) | Плагин + `tsparticles` | Интеграция через блочный редактор / шорткоды | + +## Выберите руководство + +- [Vanilla JS (чистый JavaScript)](./vanilla) +- [React](./react) +- [Vue 3](./vue3) +- [Angular](./angular) +- [Svelte](./svelte) +- [Next.js](./nextjs) +- [Nuxt](./nuxt) +- [Solid](./solid) +- [Preact](./preact) +- [Lit](./lit) +- [Qwik](./qwik) +- [jQuery](./jquery) +- [Astro](./astro) +- [Web Components](./webcomponents) +- [Stencil](./stencil) +- [Ember](./ember) +- [Riot](./riot) +- [Inferno](./inferno) +- [WordPress](./wordpress) + +Удачной разработки! diff --git a/websites/website/docs/ru/guides/inferno.md b/websites/website/docs/ru/guides/inferno.md new file mode 100644 index 00000000000..2b3aff6444b --- /dev/null +++ b/websites/website/docs/ru/guides/inferno.md @@ -0,0 +1,373 @@ +--- +title: Inferno Guide +description: Полное руководство по интеграции tsParticles с приложениями Inferno. +--- + +# Inferno Guide + +## Содержание + +1. [Установка](#установка) +2. [Базовое использование](#базовое-использование) +3. [Инициализация движка](#инициализация-движка) +4. [Пользовательская конфигурация](#пользовательская-конфигурация) +5. [Использование пресетов](#использование-пресетов) +6. [Паттерн компонента](#паттерн-компонента) +7. [Пример на TypeScript](#пример-на-typescript) + +--- + +## Установка + +Установите обёртку Inferno и движок tsParticles через npm: + +```bash +npm install @tsparticles/inferno tsparticles +``` + +Опционально установите slim-пресет для уменьшения размера сборки: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Базовое использование + +Пакет `@tsparticles/inferno` экспортирует два элемента: `ParticlesProvider` и `Particles`. Оберните ваши компоненты частиц с `ParticlesProvider`, который принимает колбэк `init` для настройки движка, затем используйте `` для отрисовки canvas частиц. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import { loadSlim } from "@tsparticles/slim"; + +const options = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +function App() { + return ( + { + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +`ParticlesProvider` должен быть предком каждого компонента ``. Он инициализирует движок один раз и предоставляет его через контекст всем дочерним элементам. + +--- + +## Инициализация движка + +`ParticlesProvider` принимает проп `init`, который получает экземпляр движка. Здесь вы загружаете функции, формы, пресеты или апдейты, необходимые вашему приложению. + +```tsx +// Лёгкий — круглые частицы, базовое движение, связи + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); +}}> + +// Полный набор — все формы, взаимодействия, эффекты + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); +}}> + +// Конкретный пресет — конфетти, фейерверк, снег, звёзды + { + const { loadConfettiPreset } = await import("@tsparticles/preset-confetti"); + await loadConfettiPreset(engine); +}}> +``` + +Использование динамического `import()` внутри колбэка включает разделение кода: модули пресетов или функций загружаются только при монтировании компонента частиц. + +--- + +## Пользовательская конфигурация + +Ниже представлена полнофункциональная конфигурация с интерактивностью, множеством типов форм и тёмным градиентным фоном. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, +}; + +function App() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +--- + +## Использование пресетов + +Пакет `@tsparticles/configs` предлагает готовые конфигурации, которые можно передать напрямую в проп `options`. Комбинируйте их с соответствующим загрузчиком пресетов в колбэке `ParticlesProvider`. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import configs from "@tsparticles/configs"; + +function App() { + return ( + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +Вы можете заменить `configs.confetti` на любой доступный пресет: `configs.basic`, `configs.fireworks`, `configs.snow`, `configs.stars` и т.д. + +--- + +## Паттерн компонента + +Для больших приложений структурируйте логику частиц в отдельный компонент с колбэком `particlesLoaded` для доступа к экземпляру `Container`. + +```tsx +import { render, Component } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +class ParticlesBackground extends Component { + private container?: Container; + + handleParticlesLoaded(container?: Container) { + this.container = container; + console.log("Частицы загружены:", container?.id); + } + + render() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); + } +} + +function App() { + return ( +
+

tsParticles + Inferno

+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +## Пример на TypeScript + +Вот полное типизированное приложение Inferno с адаптивной конфигурацией частиц и полноэкранным фоном. + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const particlesOptions: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +function handleInit(engine: Engine): Promise { + return import("@tsparticles/slim").then(({ loadSlim }) => loadSlim(engine)); +} + +function handleParticlesLoaded(container?: Container): void { + console.log("Контейнер tsParticles готов:", container?.id); +} + +function App() { + return ( + +
+

tsParticles + Inferno

+

Полноценная интеграция TypeScript

+
+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +Теперь у вас есть всё необходимое для интеграции tsParticles в приложение Inferno. Каждый пример самодостаточен и готов к копированию в ваш проект. diff --git a/websites/website/docs/ru/guides/jquery.md b/websites/website/docs/ru/guides/jquery.md new file mode 100644 index 00000000000..c6f9bc948f5 --- /dev/null +++ b/websites/website/docs/ru/guides/jquery.md @@ -0,0 +1,274 @@ +# Интеграция с jQuery + +Интегрируйте tsParticles в свои проекты на jQuery с помощью официальной обёртки плагина jQuery. + +## Установка + +### Через CDN + +Подключите jQuery, tsParticles и плагин jQuery через теги скриптов: + +```html + + + +``` + +--- + +### Через npm + сборка + +Установите необходимые пакеты: + +```bash +npm install jquery @tsparticles/jquery tsparticles +``` + +Импортируйте в ваш проект: + +```javascript +import $ from "jquery"; +import "@tsparticles/jquery"; +``` + +## Инициализация движка + +Перед рендерингом частиц движок tsParticles должен быть инициализирован с необходимыми функциями. Это делается через `$.particles.init`: + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); +})(); +``` + +> **Зачем это нужно?** tsParticles использует модульную архитектуру. `loadFull` регистрирует все встроенные формы, взаимодействия и обновления. Вы можете импортировать меньшие сборки (например, `tsparticles-slim`) для уменьшения размера. + +## Базовое использование + +После инициализации движка и готовности DOM выберите элемент-контейнер и вызовите `.particles().load()`: + +```javascript +$(document).ready(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); + + $("#tsparticles") + .particles() + .load({ + background: { + color: "#0d47a1", + }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + }, + }); +}); +``` + +Элемент-контейнер должен существовать в DOM: + +```html +
+``` + +## Пользовательская конфигурация + +Метод `.load()` принимает полный объект `ISourceOptions`. Вот комплексный пример: + +```javascript +$("#tsparticles") + .particles() + .load({ + background: { + color: "#000000", + }, + fpsLimit: 120, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + direction: "none", + enable: true, + outModes: "bounce", + speed: 4, + }, + number: { + density: { + enable: true, + }, + value: 60, + }, + opacity: { + value: 0.6, + }, + shape: { + type: ["circle", "square", "triangle"], + }, + size: { + value: { min: 2, max: 8 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + }, + interactivity: { + events: { + onClick: { + enable: true, + mode: "push", + }, + onHover: { + enable: true, + mode: "repulse", + }, + }, + modes: { + push: { + quantity: 4, + }, + repulse: { + distance: 200, + }, + }, + }, + }); +``` + +## Загрузка пресета + +Если вы установили пакет пресета (например, `tsparticles-preset-stars`), загрузите его во время инициализации движка и укажите в конфигурации: + +```bash +npm install tsparticles-preset-stars +``` + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadStarsPreset } = await import("tsparticles-preset-stars"); + await loadStarsPreset(engine); + }); + + $("#tsparticles") + .particles() + .load({ + preset: "stars", + background: { color: "#0d47a1" }, + }); +})(); +``` + +## Обработка событий и управление контейнером + +`.particles()` возвращает экземпляр плагина jQuery. Для доступа к базовому `Container` tsParticles и вызова методов, таких как `play()`, `pause()` или `destroy()`: + +```javascript +const $container = $("#tsparticles"); + +// Загрузка частиц +$container.particles().load({ + /* опции */ +}); + +// Воспроизведение/пауза через несколько секунд +setTimeout(() => { + const container = $container.particles().getContainer(); + container?.pause(); +}, 5000); +``` + +## Полный пример + +Ниже представлена полная самодостаточная HTML-страница, которая загружает tsParticles через CDN и отображает сцену с частицами с интерактивными эффектами: + +```html + + + + + + tsParticles + jQuery + + + +
+ + + + + + + +``` + +## Справочник API + +| Метод | Описание | +| ---------------------------------- | ----------------------------------------------------------- | +| `$.particles.init(fn)` | Инициализация движка с колбэком загрузчика | +| `$(el).particles()` | Создание экземпляра плагина частиц на элементе | +| `$(el).particles().load(opts)` | Загрузка и запуск конфигурации частиц | +| `$(el).particles().destroy()` | Уничтожение экземпляра частиц и очистка | +| `$(el).particles().getContainer()` | Получение базового `Container` для императивного управления | diff --git a/websites/website/docs/ru/guides/lit.md b/websites/website/docs/ru/guides/lit.md new file mode 100644 index 00000000000..a95b7e8fede --- /dev/null +++ b/websites/website/docs/ru/guides/lit.md @@ -0,0 +1,301 @@ +--- +title: Lit +description: Интеграция tsParticles с Lit с помощью официальной обёртки веб-компонента @tsparticles/lit. +--- + +# Интеграция с Lit + +Пакет `@tsparticles/lit` предоставляет пользовательский элемент ``, созданный с помощью Lit, позволяющий использовать tsParticles декларативно в любом проекте на Lit или на простой HTML-странице. + +## Установка + +```bash +npm install @tsparticles/lit tsparticles +``` + +Пакет полностью типизирован и включает реактивные контроллеры Lit для реактивного обновления опций частиц. + +## Инициализация движка + +Вызовите `initParticlesEngine` перед регистрацией компонента `` или импортом его в ваше приложение. Это должно произойти ровно один раз. + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadFull } from "tsparticles"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +Для оптимизации размера сборки импортируйте только те функции, которые нужны вашему проекту: + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadBasic } from "@tsparticles/basic"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +void initParticlesEngine(async (engine) => { + await loadBasic(engine); + await loadConfettiPreset(engine); +}); +``` + +## Базовое использование + +После инициализации движка используйте элемент `` в любом шаблоне Lit или HTML-файле: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private options = { + background: { + color: "#0d1117", + }, + particles: { + number: { value: 60 }, + color: { value: "#58a6ff" }, + links: { + enable: true, + color: "#58a6ff", + }, + move: { enable: true, speed: 2 }, + }, + }; + + render() { + return html` `; + } +} +``` + +Синтаксис `.options` (с точкой) — это привязка свойства Lit, гарантирующая, что объект передаётся по ссылке, а не сериализуется как атрибут. + +## Использование в простом HTML + +После сборки или загрузки `@tsparticles/lit` элемент работает и в простом HTML: + +```html + + + + + + + + + +``` + +Вы можете передать минимальный объект опций как JSON-атрибут: + +```html + +``` + +## Пользовательская конфигурация + +Передайте полную конфигурацию tsParticles как свойство Lit: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-particles") +class MyParticles extends LitElement { + @property({ type: Object }) + options: ISourceOptions = { + background: { + color: "#0d1117", + }, + fpsLimit: 120, + fullScreen: { + enable: true, + zIndex: -1, + }, + particles: { + color: { + value: ["#ff5733", "#33ff57", "#3357ff"], + }, + links: { + color: "#ffffff", + enable: true, + opacity: 0.3, + distance: 150, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + }, + number: { + value: 100, + density: { + enable: true, + }, + }, + opacity: { + value: 0.6, + animation: { + enable: true, + speed: 0.5, + minimumValue: 0.1, + }, + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 2, + minimumValue: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + }, + modes: { + grab: { + distance: 180, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + }; + + render() { + return html` `; + } +} +``` + +## Обработка событий + +Слушайте пользовательское событие `particles-loaded`, которое генерируется элементом ``: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import type { Container } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private handleParticlesLoaded(e: CustomEvent) { + const container = e.detail; + console.log("Частицы загружены:", container); + container?.refresh(); + } + + render() { + return html` `; + } +} +``` + +## Пример на TypeScript + +Полностью типизированный элемент Lit с `initParticlesEngine`, реактивными опциями и обработкой событий: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import { initParticlesEngine } from "@tsparticles/lit"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import "@tsparticles/lit"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +@customElement("particles-background") +class ParticlesBackground extends LitElement { + @property({ type: Object }) + options: ISourceOptions = {}; + + @property({ type: Boolean, attribute: "fullscreen" }) + fullscreen = true; + + protected onParticlesLoaded(e: CustomEvent) { + console.log("Контейнер готов:", e.detail.id); + } + + render() { + return html` + + + `; + } +} +``` + +## Динамические обновления + +Поскольку `` использует реактивные свойства Lit, изменение свойства `options` автоматически обновляет частицы: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("dynamic-particles") +class DynamicParticles extends LitElement { + @state() + private theme: "light" | "dark" = "dark"; + + private get options(): ISourceOptions { + return this.theme === "dark" + ? { + background: { color: "#0d1117" }, + particles: { color: { value: "#58a6ff" } }, + } + : { + background: { color: "#ffffff" }, + particles: { color: { value: "#0969da" } }, + }; + } + + private toggleTheme() { + this.theme = this.theme === "dark" ? "light" : "dark"; + } + + render() { + return html` + + + `; + } +} +``` + +Компонент отслеживает свойство `options` и вызывает `refresh()` внутри при каждом его изменении, плавно обновляя конфигурацию частиц во время выполнения. diff --git a/websites/website/docs/ru/guides/nextjs.md b/websites/website/docs/ru/guides/nextjs.md new file mode 100644 index 00000000000..268b623d15b --- /dev/null +++ b/websites/website/docs/ru/guides/nextjs.md @@ -0,0 +1,492 @@ +--- +title: Интеграция с Next.js +description: Пошаговое руководство по интеграции tsParticles в приложение Next.js с использованием App Router. +--- + +# Интеграция с Next.js + +В этом руководстве рассматривается интеграция tsParticles в проект Next.js с использованием **App Router** (Next.js 13+). Для легаси Pages Router смотрите раздел [Pages Router (легаси)](#pages-router-легаси) внизу. + +## Установка + +Установите обёртку `@tsparticles/react` и полный движок `tsparticles` (или slim-сборку для меньших размеров): + +```bash +npm install @tsparticles/react tsparticles +``` + +Если вы предпочитаете меньшую сборку `@tsparticles/slim`: + +```bash +npm install @tsparticles/react @tsparticles/slim +``` + +## Базовое использование (App Router) + +Компоненты App Router в Next.js по умолчанию серверные. Поскольку tsParticles требует браузерный API `canvas`, необходимо пометить компонент директивой `"use client"`. + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesBackground() { + const particlesLoaded = useCallback((container?: Container) => { + console.log("Частицы загружены", container); + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }), + [], + ); + + return ; +} +``` + +Создайте этот файл как `components/particles-background.tsx` и импортируйте его на любую страницу или в макет. Поскольку файл начинается с `"use client"`, он будет отрендерен на клиенте — именно там, где должен работать tsParticles. + +## Переключение темы + +Комбинируйте tsParticles с переключателями тем Next.js, получая опции из текущего состояния темы: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useMemo, useState, useCallback } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ThemeAwareParticles() { + const [theme, setTheme] = useState<"light" | "dark">("dark"); + + const toggleTheme = useCallback(() => { + setTheme((t) => (t === "dark" ? "light" : "dark")); + }, []); + + const particlesLoaded = useCallback((_container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { + color: theme === "dark" ? "#000000" : "#ffffff", + }, + particles: { + color: { value: theme === "dark" ? "#ffffff" : "#000000" }, + number: { value: 100 }, + links: { + enable: true, + color: theme === "dark" ? "#ffffff" : "#000000", + }, + move: { enable: true }, + }, + }), + [theme], + ); + + return ( + <> + + + + ); +} +``` + +Объект `options` пересоздаётся через `useMemo` при каждом изменении `theme`, поэтому canvas обновляется автоматически. + +## Эффект конфетти + +Используйте `@tsparticles/preset-confetti` для праздничного конфетти по событиям, например, по клику на кнопку: + +```bash +npm install @tsparticles/preset-confetti +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Container, ISourceOptions, Engine } from "@tsparticles/engine"; + +export default function ConfettiButton() { + const [active, setActive] = useState(false); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadConfettiPreset(engine); + }, []); + + const particlesLoaded = useCallback( + async (container?: Container) => { + if (active && container) { + await container.play(); + } + }, + [active], + ); + + const options: ISourceOptions = useMemo( + () => ({ + preset: "confetti", + fullScreen: { zIndex: 1000 }, + }), + [], + ); + + const handleCelebrate = useCallback(() => { + setActive(true); + setTimeout(() => setActive(false), 5000); + }, []); + + return ( + <> + {active && } + + + ); +} +``` + +Колбэк `init` загружает пресет конфетти в движок до создания частиц. + +## Эффект фейерверка + +Аналогично, пресет фейерверка создаёт зрелищный салют: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; +import type { Container, Engine } from "@tsparticles/engine"; + +export default function FireworksBackground() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFireworksPreset(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options = useMemo( + () => ({ + preset: "fireworks" as const, + fullScreen: { zIndex: -1 }, + background: { + color: "#000", + }, + }), + [], + ); + + return ; +} +``` + +## Полный пример TypeScript с Container Ref + +Получите доступ к экземпляру `Container` для программного управления анимацией (воспроизведение, пауза, уничтожение, экспорт изображения): + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +export default function ControllableParticles() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFull(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + fpsLimit: 120, + interactivity: { + events: { + onClick: { enable: true, mode: "push" }, + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + push: { quantity: 4 }, + repulse: { distance: 100 }, + }, + }, + particles: { + color: { value: "#ff0000" }, + links: { + enable: true, + color: "#ff0000", + distance: 150, + }, + move: { enable: true, speed: 2 }, + number: { value: 60 }, + size: { value: { min: 1, max: 5 } }, + }, + }), + [], + ); + + const handlePause = useCallback(() => { + containerRef.current?.pause(); + }, []); + + const handlePlay = useCallback(() => { + containerRef.current?.play(); + }, []); + + return ( +
+ +
+ + +
+
+ ); +} +``` + +Ключевые моменты: + +- `particlesInit` загружает функции движка (выполняется только один раз за монтирование компонента). +- `particlesLoaded` срабатывает каждый раз при полной инициализации контейнера. +- `containerRef` хранит экземпляр `Container`, чтобы вы могли вызывать его методы позже. + +## Производительность: useMemo и useCallback + +Всегда оборачивайте статические или редко изменяющиеся опции в `useMemo`, а обработчики событий — в `useCallback`, чтобы предотвратить ненужные повторные рендеры canvas: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function PerformanceExample() { + const [particlesCount, setParticlesCount] = useState(80); + + // Стабильный колбэк — не пересоздаётся без изменения зависимостей + const particlesLoaded = useCallback((container?: Container) => { + console.log("Контейнер готов", container?.id); + }, []); + + // Стабильный объект опций — предотвращает переинициализацию canvas + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: particlesCount }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [particlesCount], + ); + + return ( +
+ + +
+ ); +} +``` + +Без этих оптимизаций каждый повторный рендер родителя создавал бы новый объект `options`, вызывая пересоздание canvas. + +## Интеграция со страницей + +Добавьте фон с частицами в макет страницы, не затрагивая содержимое страницы: + +```tsx +// app/layout.tsx (серверный компонент) +import dynamic from "next/dynamic"; + +const ParticlesBackground = dynamic(() => import("@/components/particles-background"), { ssr: false }); + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + +
{children}
+ + + ); +} +``` + +Используйте `dynamic()` с `ssr: false`, чтобы гарантировать, что компонент никогда не выполняется во время серверного рендеринга. Canvas частиц располагается позади основного содержимого через CSS `z-index`. + +## Несколько экземпляров + +Вы можете отобразить несколько независимых компонентов `Particles` на одной странице, каждый со своей конфигурацией: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +function ParticlesGallery() { + const loaded = useCallback((c?: Container) => {}, []); + + const redOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#1a0000" }, + particles: { + color: { value: "#ff0000" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + const blueOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#00001a" }, + particles: { + color: { value: "#0000ff" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + return ( +
+ + +
+ ); +} +``` + +Каждый компонент `Particles` создаёт независимый canvas со своим циклом анимации. Установите `fullScreen: false` и задайте каждому фиксированную высоту, чтобы они сосуществовали в потоке документа. + +## Pages Router (легаси) + +Если вы используете **Pages Router** Next.js (директория `pages/`), подход аналогичен, но без директивы `"use client"`. Вместо этого используйте динамический импорт в компоненте страницы: + +```tsx +// pages/index.tsx +import dynamic from "next/dynamic"; +import type { NextPage } from "next"; + +const ParticlesComponent = dynamic(() => import("../components/particles-component"), { ssr: false }); + +const Home: NextPage = () => { + return ( +
+ +

Добро пожаловать

+
+ ); +}; + +export default Home; +``` + +Сам компонент (`components/particles-component.tsx`) — это обычный React-компонент: + +```tsx +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesComponent() { + const particlesLoaded = useCallback((container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 80 }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [], + ); + + return ; +} +``` + +Обратите внимание, что Pages Router **не требует** `"use client"`, поскольку компоненты страниц по умолчанию уже рендерятся на клиенте. + +## Устранение неполадок + +| Симптом | Причина | Исправление | +| ----------------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------- | +| Пустая белая страница | SSR-рендеринг модуля, зависящего от canvas | Используйте `dynamic(..., { ssr: false })` или обёртку в клиентский компонент | +| Canvas не отображается | Контейнер имеет нулевую высоту | Установите `fullScreen: { zIndex: -1 }` или задайте явные размеры | +| Изменение опций не отражается | Не создана новая ссылка на объект | Используйте `useMemo` с правильным массивом зависимостей | +| Пресет не работает | Пресет не загружен до инициализации контейнера | Вызовите `loadXPreset(engine)` внутри колбэка `init` | + +## Следующие шаги + +- Просмотрите [Интерактивные демо](/demos/) для готовых конфигураций. +- Прочтите полный [Справочник параметров](/options/) для каждого доступного параметра. +- Посетите страницу [Пресеты](/demos/presets) для дополнительных готовых пресетов, таких как снег, звёзды и светлячки. diff --git a/websites/website/docs/ru/guides/nuxt.md b/websites/website/docs/ru/guides/nuxt.md new file mode 100644 index 00000000000..fb890bf2187 --- /dev/null +++ b/websites/website/docs/ru/guides/nuxt.md @@ -0,0 +1,463 @@ +--- +title: Интеграция с Nuxt +description: Пошаговое руководство по интеграции tsParticles в приложение Nuxt 3 / Nuxt 4. +--- + +# Интеграция с Nuxt + +В этом руководстве рассматривается интеграция tsParticles в проект **Nuxt 3** (и Nuxt 4) с использованием официальной обёртки `@tsparticles/vue3`. Nuxt работает как на сервере, так и на клиенте, поэтому необходимо защитить компоненты частиц от SSR. + +## Установка + +Установите обёртку Vue 3 и выбранную сборку движка: + +```bash +npm install @tsparticles/vue3 tsparticles +``` + +Для меньшей сборки установите `@tsparticles/slim` вместо `tsparticles`: + +```bash +npm install @tsparticles/vue3 @tsparticles/slim +``` + +## Базовое использование + +Nuxt по умолчанию рендерит компоненты на сервере. Поскольку tsParticles требует браузерный API `canvas`, необходимо обернуть компонент `` в тег ``: + +```vue + + + + + +``` + +Обёртка `` гарантирует, что компонент `` монтируется только в браузере, предотвращая несоответствия гидратации. + +## Конфигурация + +Используйте полноценный тип `ISourceOptions` для типобезопасной конфигурации. Вы можете определить опции встроенно или импортировать их из отдельного файла конфигурации: + +```vue + +``` + +## Эффект снега + +Создайте зимний эффект снегопада с помощью пресета snow: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +Поскольку пресет загружается с помощью `await` верхнего уровня в ` +``` + +Доступные режимы взаимодействия: `grab`, `bubble`, `connect`, `repulse`, `push`, `remove`, `attract` и `slow`. + +## Обработка событий + +Компонент `` генерирует несколько событий жизненного цикла: + +```vue + + + +``` + +| Событие | Полезные данные | Описание | +| -------------------- | --------------- | --------------------------------------------------------------- | +| `@particles-init` | `Engine` | Срабатывает один раз при инициализации движка tsParticles | +| `@particles-loaded` | `Container` | Срабатывает каждый раз при загрузке или перезагрузке контейнера | +| `@particles-destroy` | отсутствует | Срабатывает при уничтожении контейнера | + +## Полный пример TypeScript + +Полный типизированный компонент с явными импортами и управлением жизненным циклом: + +```vue + + + + + +``` + +## Интеграция со страницей + +Добавьте фон с частицами на конкретную страницу Nuxt, разместив компонент в шаблоне страницы: + +```vue + + + + + +``` + +Если вы хотите, чтобы частицы были на **каждой** странице, добавьте компонент в `layouts/default.vue` вместо отдельных страниц. + +## Заметки о Nuxt 4 + +Nuxt 4 сохраняет обратную совместимость с шаблонами `` и ` +``` + +## Устранение неполадок + +| Симптом | Причина | Исправление | +| --------------------------------------------------- | --------------------------------------- | -------------------------------------------------------------------- | +| Пустой экран / ошибка гидратации | `` отрендерен на сервере | Обернуть в `` | +| Пресет не действует | Пресет не загружен до монтирования | Вызвать `loadXPreset()` с `await` верхнего уровня в ` + +``` + +Движок инициализируется один раз и используется всеми экземплярами `` в вашем приложении. + +--- + +## Базовое использование + +После инициализации движка используйте компонент `` в вашем шаблоне. Передайте конфигурацию в виде JSON-строки объекта опций или ссылки на свойство вашего компонента. + +```html + + + + + +``` + +--- + +## Условный рендеринг + +Используйте директиву `if={}` Riot со свойством состояния, чтобы отложить рендеринг компонента частиц до завершения инициализации движка. Это предотвращает смещение макета и гарантирует, что компонент получит готовый движок. + +```html + + + + + +``` + +Вызов `this.update()` запускает повторный рендер, и тег `` появляется после разрешения промиса. + +--- + +## Использование пресетов + +Пакет `@tsparticles/configs` предоставляет готовые конфигурации для распространённых эффектов, таких как конфетти, фейерверк, снег и звёзды. Используйте их напрямую как объект опций. + +```html + + + + + +``` + +Доступные пресеты: `basic`, `confetti`, `fireworks`, `snow`, `stars` и другие. Каждый пресет требует соответствующий пакет пресета, загруженный в колбэке движка. Например, `configs.fireworks` требует `loadFireworksPreset`. + +--- + +## Пользовательская конфигурация + +Создайте пользовательскую конфигурацию с интерактивностью, множеством форм и расширенными опциями анимации. + +```html + + + + + +``` + +--- + +## Полный компонент + +Ниже представлен полный файл `.riot`, объединяющий всё вместе: инициализацию движка в `onBeforeMount`, условный рендеринг с состоянием, богатую конфигурацию с интерактивностью и колбэк `particlesLoaded` через встроенную поддержку событий загрузки. + +```html + +
+

tsParticles + Riot.js

+ + {#if state.particlesInitialized} + + {:else} +

Загрузка движка частиц...

+ {/if} +
+ + + + +
+``` + +--- + +Теперь у вас есть всё необходимое для интеграции tsParticles в приложение Riot.js. Каждый пример самодостаточен и готов к копированию в ваш проект. diff --git a/websites/website/docs/ru/guides/solid.md b/websites/website/docs/ru/guides/solid.md new file mode 100644 index 00000000000..14e155c427b --- /dev/null +++ b/websites/website/docs/ru/guides/solid.md @@ -0,0 +1,512 @@ +--- +title: Интеграция с SolidJS +description: Пошаговое руководство по интеграции tsParticles в приложение SolidJS с использованием официальной обёртки @tsparticles/solid. +--- + +# Интеграция с SolidJS + +В этом руководстве рассматривается интеграция tsParticles в проект **SolidJS** с использованием официальной обёртки `@tsparticles/solid`. Тонкозернистая реактивность SolidJS хорошо работает с tsParticles — изменения опций вызывают целевые обновления canvas без полной переинициализации. + +## Установка + +Установите обёртку SolidJS и выбранную сборку движка: + +```bash +npm install @tsparticles/solid tsparticles +``` + +Для меньшей сборки используйте `@tsparticles/slim`: + +```bash +npm install @tsparticles/solid @tsparticles/slim +``` + +## Базовое использование + +SolidJS работает полностью в браузере (без SSR), поэтому вам не нужно защищаться от серверного рендеринга. Однако движок должен быть инициализирован асинхронно перед рендерингом частиц. + +Используйте `initParticlesEngine` внутри `onMount` для загрузки функций движка, затем условно рендерите компонент `` с ``: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [initialized, setInitialized] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setInitialized(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +Компонент `` гарантирует, что элемент `` вставляется в DOM только после готовности движка. + +## Инициализация движка + +Функция `initParticlesEngine` принимает колбэк, который получает экземпляр `Engine`. Используйте этот колбэк для регистрации функций, необходимых вашей конфигурации: + +```tsx +import { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import { loadSlim } from "@tsparticles/slim"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Engine } from "@tsparticles/engine"; + +// Минимально — только базовые формы и движение +initParticlesEngine((engine: Engine) => loadSlim(engine)).then(() => { + console.log("Движок готов (slim)"); +}); + +// Полный — все функции включены +initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => { + console.log("Движок готов (full)"); +}); + +// Только пресет — только функции, необходимые для конкретного пресета +initParticlesEngine((engine: Engine) => loadConfettiPreset(engine)).then(() => { + console.log("Пресет конфетти загружен"); +}); +``` + +Вызовите `initParticlesEngine` один раз в вашем приложении — обычно в `onMount` корневого компонента. Экземпляр движка кешируется, поэтому последующие вызовы возвращаются немедленно. + +## Условный рендеринг + +Используйте управляющий поток `` SolidJS для отложенного рендеринга до инициализации движка: + +```tsx +import { createSignal, Show, onMount } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import type { Engine } from "@tsparticles/engine"; +import type { Component } from "solid-js"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + Загрузка частиц...

}> + +
+ ); +}; +``` + +Проп `fallback` показывает индикатор загрузки во время инициализации движка. + +## Использование пресетов + +Используйте `@tsparticles/configs` для быстрых, готовых конфигураций: + +```bash +npm install @tsparticles/configs +``` + +```tsx +import configs from "@tsparticles/configs"; +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + +
+ + +
+
+ ); +}; + +export default App; +``` + +Доступные конфиги: `basic`, `bubbles`, `snow`, `stars`, `fireworks`, `confetti`, `links` и другие. + +## Интерактивные частицы + +Добавьте взаимодействия по клику и наведению, настроив раздел `interactivity`: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 60 }, + links: { enable: true, distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 4 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +- **Режимы наведения**: `grab`, `bubble`, `repulse`, `attract`, `slow`, `connect` +- **Режимы клика**: `push`, `remove`, `repulse`, `bubble`, `attract`, `pause` + +## Пользовательская конфигурация + +Полная пользовательская конфигурация с множеством форм частиц, цветовых палитр и настроек движения: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0a0a23" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { enable: true, rotateX: 600, rotateY: 1200 }, + }, + number: { + value: 40, + density: { enable: true }, + }, + opacity: { + value: { min: 0.3, max: 0.8 }, + animation: { + enable: true, + speed: 0.5, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + animation: { + enable: true, + speed: 2, + sync: false, + }, + }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.3, + width: 1, + }, + shape: { + type: ["circle", "square", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + twinkle: { + particles: { + enable: true, + frequency: 0.05, + opacity: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "bubble" }, + }, + modes: { + repulse: { distance: 120 }, + bubble: { distance: 200, size: 10, opacity: 0.8 }, + }, + }, + detectRetina: true, + }; + + return ( + + + + ); +}; + +export default App; +``` + +## Полный пример TypeScript + +Полный типизированный компонент с ссылкой на контейнер, инициализацией движка и ручным управлением: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [container, setContainer] = createSignal(undefined); + const [paused, setPaused] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#1a1a2e" }, + particles: { + color: { value: "#e94560" }, + number: { value: 80 }, + links: { enable: true, color: "#e94560", distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 5 } }, + }, + }; + + const particlesLoaded = (c: Container) => { + setContainer(c); + }; + + const togglePause = () => { + const c = container(); + if (c) { + if (paused()) { + c.play(); + } else { + c.pause(); + } + setPaused(!paused()); + } + }; + + return ( + + + + + ); +}; + +export default App; +``` + +## Динамические опции с сигналами + +Одно из преимуществ SolidJS — тонкозернистая реактивность: вы можете использовать сигналы для управления опциями частиц, и canvas будет эффективно обновляться: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [color, setColor] = createSignal("#ff0000"); + const [particleCount, setParticleCount] = createSignal(60); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + // опции — обычный объект; он будет реактивно читаться + // через внутреннее отслеживание компонента Particles + const options = (): ISourceOptions => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#000" }, + particles: { + color: { value: color() }, + number: { value: particleCount() }, + links: { enable: true, color: color() }, + move: { enable: true }, + }, + }); + + return ( + + {}} /> +
+ + +
+
+ ); +}; + +export default App; +``` + +Поскольку `options` — это функция, которая обращается к сигналам, при каждом изменении `color()` или `particleCount()` компонент `` получает новый объект опций и применяет только изменённые свойства к существующему canvas. + +## Пресет с пользовательскими переопределениями + +Загрузите пресет, затем объедините с пользовательскими переопределениями для индивидуального эффекта: + +```tsx +import { loadSnowPreset } from "@tsparticles/preset-snow"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadSnowPreset(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + preset: "snow", + fullScreen: { zIndex: -1 }, + background: { color: "#0d0d2b" }, + particles: { + // Переопределяем цвет снега на синий + color: { value: "#88ccff" }, + // Увеличиваем количество хлопьев + number: { value: 300 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +Пресет предоставляет значения по умолчанию для каждой опции, а ваши переопределения объединяются поверх — нужно указать только те свойства, которые вы хотите изменить. + +## Устранение неполадок + +| Симптом | Причина | Исправление | +| ----------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------ | +| Пустой DOM-элемент | Движок не инициализирован до рендеринга | Оберните `` в `` | +| Частицы не видны | Отсутствует `move.enable` или `number.value` | Убедитесь, что `particles.move.enable: true` и `particles.number.value > 0` | +| Canvas позади контента | Отсутствует `zIndex` в fullScreen | Используйте `fullScreen: { zIndex: -1 }` | +| Изменение опций не отражается | Ссылка на объект не меняется | Оберните опции в функцию или store; избегайте статических объектов | +| Движок не найден | Отсутствует импорт `loadFull` или `loadSlim` | Установите `tsparticles` или `@tsparticles/slim` и вызовите `loadFull(engine)` | + +## Следующие шаги + +- Изучите [площадку Configs](/playground/configs) для готовых конфигураций. +- Прочтите [Справочник параметров](/options/) для полного списка параметров. +- Просмотрите [исходный код SolidJS](https://github.com/tsparticles/solid) на GitHub для внутренностей обёртки. diff --git a/websites/website/docs/ru/guides/stencil.md b/websites/website/docs/ru/guides/stencil.md new file mode 100644 index 00000000000..5d8b078c779 --- /dev/null +++ b/websites/website/docs/ru/guides/stencil.md @@ -0,0 +1,359 @@ +--- +title: Stencil Guide +description: Полное руководство по интеграции tsParticles с компонентами Stencil. +--- + +# Stencil Guide + +## Содержание + +1. [Установка](#установка) +2. [Регистрация пользовательских элементов](#регистрация-пользовательских-элементов) +3. [Базовое использование](#базовое-использование) +4. [Инициализация движка](#инициализация-движка) +5. [Пользовательская конфигурация](#пользовательская-конфигурация) +6. [Жизненный цикл компонента](#жизненный-цикл-компонента) +7. [Пример на TypeScript](#пример-на-typescript) + +--- + +## Установка + +Установите обёртку Stencil и движок tsParticles через npm: + +```bash +npm install @tsparticles/stencil tsparticles +``` + +Опционально установите пакет пресета для уменьшения ручной конфигурации: + +```bash +npm install @tsparticles/slim +``` + +--- + +## Регистрация пользовательских элементов + +Пакет `@tsparticles/stencil` предоставляет функцию `defineCustomElements`, которая регистрирует пользовательский элемент `` в браузере. Вызовите её один раз перед использованием компонента где-либо в вашем приложении. + +```tsx +import { defineCustomElements } from "@tsparticles/stencil/loader"; + +// Регистрация элемента +defineCustomElements(); +``` + +Для проектов Stencil, использующих ленивую загрузку, вызовите это внутри `componentWillLoad` или в корневом компоненте вашего приложения, чтобы гарантировать доступность элемента до рендеринга. + +--- + +## Базовое использование + +После регистрации пользовательского элемента вы можете использовать `` в JSX с пропом `options` и колбэком `init` для загрузки необходимых функций движка. + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +@Component({ tag: "my-particles" }) +export class MyParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## Инициализация движка + +Проп `init` получает экземпляр движка и позволяет загрузить необходимые функции. Это рекомендуемое место для вызова `loadSlim`, `loadFull` или отдельных плагинов обновлений/взаимодействий. + +```tsx +import { loadSlim } from "@tsparticles/slim"; +import { loadFull } from "tsparticles"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// Вариант A: лёгкий (круги, базовое движение, связи) +init={async engine => { await loadSlim(engine); }} + +// Вариант B: полный набор (все формы, эффекты, пресеты) +init={async engine => { await loadFull(engine); }} + +// Вариант C: пресеты (конфетти, фейерверк, снег, звёзды) +init={async engine => { await loadConfettiPreset(engine); }} +``` + +Экземпляр движка также доступен после инициализации через атрибут `container-id`, позволяя программно управлять системой частиц позже при необходимости. + +--- + +## Пользовательская конфигурация + +Ниже представлена полная конфигурация с интерактивностью, множеством типов форм и режимами наведения/клика. + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const fullOptions: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { + color: "#0f0f23", + }, +}; + +@Component({ tag: "app-particles" }) +export class AppParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## Жизненный цикл компонента + +В Stencil рекомендуемый хук жизненного цикла для одноразовой настройки — `componentWillLoad`. Используйте его для регистрации пользовательских элементов и управления состоянием инициализации, чтобы компонент `` рендерился только после подготовки движка. + +```tsx +import { Component, h, State } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ tag: "app-root" }) +export class AppRoot { + @State() private engineReady = false; + + private options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { + enable: true, + speed: 1, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#1a1a2e" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.engineReady = true; + } + + render() { + return ( +
+

tsParticles + Stencil

+ {this.engineReady && ( + { + await loadSlim(engine); + }} + /> + )} +
+ ); + } +} +``` + +Использование `@State()` гарантирует повторный рендер компонента, когда движок становится готов, а условный рендеринг предотвращает монтирование контейнера частиц до определения пользовательского элемента. + +--- + +## Пример на TypeScript + +Вот полный типизированный компонент приложения Stencil, который интегрирует tsParticles с slim-пресетом, интерактивностью при наведении и пользовательской тёмной темой. + +```tsx +import { Component, h, State, Prop } from "@stencil/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ + tag: "app-home", + styleUrl: "app-home.css", + shadow: true, +}) +export class AppHome { + @State() private initialized = false; + + @Prop() readonly title: string = "Добро пожаловать"; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.initialized = true; + } + + private handleInit = async (engine: Engine): Promise => { + await loadSlim(engine); + }; + + private handleLoaded = async (container?: Container): Promise => { + this.container = container; + console.log("Контейнер частиц загружен:", container?.id); + }; + + render() { + return ( +
+

{this.title}

+

На базе tsParticles и Stencil

+ + {this.initialized && ( + + )} +
+ ); + } +} +``` + +Событие `particlesLoaded` срабатывает после рендеринга первого кадра, предоставляя доступ к экземпляру `Container` для программного управления (воспроизведение, пауза, остановка, переключение тем). + +--- + +Теперь у вас есть всё необходимое для интеграции tsParticles в приложение Stencil. Каждый пример самодостаточен и готов к копированию в ваш проект. diff --git a/websites/website/docs/ru/guides/svelte.md b/websites/website/docs/ru/guides/svelte.md new file mode 100644 index 00000000000..23cfeee588b --- /dev/null +++ b/websites/website/docs/ru/guides/svelte.md @@ -0,0 +1,580 @@ +--- +title: Интеграция с Svelte +description: Пошаговое руководство по интеграции tsParticles в приложения Svelte и SvelteKit с использованием @tsparticles/svelte. +--- + +# Интеграция с Svelte + +Пакет `@tsparticles/svelte` предоставляет нативный компонент Svelte для tsParticles. Это руководство охватывает Svelte (с Vite) и SvelteKit, включая реактивные опции, обработку событий и несколько экземпляров. + +--- + +## Установка + +```bash +npm install @tsparticles/svelte @tsparticles/engine +``` + +Для полной сборки или пресетов: + +```bash +npm install tsparticles +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +``` + +--- + +## Базовое использование + +```svelte + + + +``` + +--- + +## Инициализация движка + +Передайте обработчик события `on:init` для загрузки плагинов и пресетов, необходимых вашему приложению: + +```svelte + + + +``` + +Альтернативно, используйте утилиту `initParticlesEngine` перед монтированием: + +```svelte + + +{#if ready} + +{/if} +``` + +--- + +## Эффект снега + +```bash +npm install @tsparticles/preset-snow +``` + +```svelte + + + +``` + +Настройте поведение пресета, объединив дополнительные опции: + +```svelte + +``` + +--- + +## Эффект звёзд + +```bash +npm install @tsparticles/preset-stars +``` + +```svelte + + + +``` + +--- + +## Интерактивные частицы + +Добавьте взаимодействие по наведению мыши и клику: + +```svelte + + + +``` + +--- + +## Обработка событий + +```svelte + + +
+ + + +
+ + +``` + +| Событие | Деталь | Срабатывает | +| -------------------- | ----------- | ---------------------------------- | +| `on:init` | `Engine` | После инициализации движка | +| `on:particlesLoaded` | `Container` | После полной готовности контейнера | + +--- + +## Пример на TypeScript + +Полный типизированный компонент: + +```svelte + + + +``` + +--- + +## Динамические опции + +Реактивные опции обновляют частицы без пересоздания экземпляра: + +```svelte + + +
+ +
+ + +``` + +Реактивное объявление `$:` пересчитывает `options` при каждом изменении `color`, и компонент `Particles` автоматически применяет новую конфигурацию. + +--- + +## Несколько экземпляров + +Отобразите несколько независимых систем частиц на одной странице: + +```svelte + + +
+
+ +
+
+ +
+
+``` + +Каждый компонент `` получает свой собственный `id`, canvas и контекст движка. + +--- + +## Использование в SvelteKit + +В SvelteKit canvas требует браузерного окружения. Отключите SSR для компонента: + +```svelte + + +{#if Component} + +{/if} +``` + +Или оберните импорт в клиентский компонент. Для SvelteKit 2+ также можно использовать исключения SSR `vite-plugin-svelte`. + +--- + +## Справочник API + +| Проп | Тип | По умолчанию | Описание | +| --------- | ---------------- | --------------- | -------------------------- | +| `id` | `string` | `"tsparticles"` | ID элемента canvas | +| `options` | `ISourceOptions` | `{}` | Объект конфигурации частиц | +| `url` | `string` | — | URL удалённой JSON конфиг. | + +| Событие | Деталь | Описание | +| -------------------- | ----------- | ------------------------------------------------------------------------ | +| `on:init` | `Engine` | Срабатывает при инициализации движка (используйте для загрузки плагинов) | +| `on:particlesLoaded` | `Container` | Срабатывает при полной готовности контейнера | + +--- + +## Устранение неполадок + +- **Canvas не виден** — Убедитесь, что родительский контейнер имеет явные размеры (`height: 100%`, `height: 100vh` или фиксированное значение в пикселях). +- **`loadFull is not a function`** — Проверьте, что `tsparticles` установлен и вы импортируете `loadFull` из `tsparticles` (не из `@tsparticles/engine`). +- **Реактивность не работает** — Убедитесь, что `options` — реактивная переменная (`$:` или `let`, привязанная к реактивному источнику). Обычные `const` значения не будут обновляться. +- **SvelteKit пустой экран** — Импортируйте `@tsparticles/svelte` динамически или используйте защиту `browser` как показано в разделе SvelteKit выше. +- **Ошибки TypeScript для `event.detail`** — Используйте типы `CustomEvent` и `CustomEvent` для обработчиков событий. diff --git a/websites/website/docs/ru/guides/vanilla.md b/websites/website/docs/ru/guides/vanilla.md new file mode 100644 index 00000000000..3d3e2c33234 --- /dev/null +++ b/websites/website/docs/ru/guides/vanilla.md @@ -0,0 +1,889 @@ +--- +title: Руководство по Vanilla JS +description: Полное руководство по интеграции tsParticles с чистым JavaScript. +--- + +# Руководство по Vanilla JS + +## Содержание + +1. [Начало работы](#начало-работы) +2. [Базовые частицы](#базовые-частицы) +3. [Эффект конфетти](#эффект-конфетти) +4. [Эффект фейерверка](#эффект-фейерверка) +5. [Эффект лент](#эффект-лент) +6. [Эффект снега](#эффект-снега) +7. [Эффект сети / связей](#эффект-сети-связей) +8. [Эффект звезд](#эффект-звезд) +9. [Пользовательская конфигурация](#пользовательская-конфигурация) +10. [Несколько контейнеров](#несколько-контейнеров) +11. [Динамическое управление](#динамическое-управление) + +--- + +## Начало работы + +### CDN (быстрый старт) + +Добавьте элемент `
` в качестве контейнера и теги скриптов в ваш HTML. Вам понадобится как минимум движок + один из пакетов, и необходимо вызвать загрузчик до `tsParticles.load()`. + +```html + + + + + + tsParticles – Начало работы + + + +
+ + + + + + +``` + +### npm + +```bash +npm install @tsparticles/engine @tsparticles/slim +``` + +Затем импортируйте и используйте: + +```javascript +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +(async () => { + await loadSlim(tsParticles); + + await tsParticles.load({ + id: "tsparticles", + options: { + /* ... */ + }, + }); +})(); +``` + +> **Примечание:** `@tsparticles/engine` сам по себе ничего не рисует. Вам необходимо установить один из пакетов (`@tsparticles/slim` рекомендуется) или отдельные плагины, чтобы получить видимые формы. + +--- + +## Базовые частицы + +Минимальная конфигурация, отображающая 100 частиц круглой формы со случайными цветами и плавным движением. В версии 4 цвета частиц задаются через `paint` вместо старого свойства `color`. + +```html + + + + + + Базовые частицы + + + +
+ + + + + + +``` + +--- + +## Эффект конфетти + +Используйте специальный пакет `@tsparticles/confetti` для праздничного выброса частиц одним вызовом функции. + +```html + + + + + + Конфетти + + + + + + + + + +``` + +--- + +## Эффект фейерверка + +Шоу фейерверков с использованием специального пакета `@tsparticles/fireworks` со звуковыми эффектами. + +```html + + + + + + Фейерверк + + + + + + + +``` + +--- + +## Эффект лент + +Используйте специальный пакет `@tsparticles/ribbons` для анимации лент, реагирующих на положение мыши. + +```html + + + + + + Ленты + + + + + + + +``` + +--- + +## Эффект снега + +Нежные падающие снежинки с использованием каталога пресетов `@tsparticles/configs`. + +```html + + + + + + Эффект снега + + + +
+ + + + + + + +``` + +Альтернативно, используя отдельный пакет пресета: + +```html + + + + +``` + +--- + +## Эффект сети / связей + +Классическая визуализация соединённых узлов с интерактивностью мыши. Пакет `@tsparticles/slim` включает взаимодействие связей и режим захвата мышью. + +```html + + + + + + Сеть / Связи + + + +
+ + + + + + +``` + +--- + +## Эффект звезд + +Звёздное небо с использованием каталога пресетов `@tsparticles/configs`. + +```html + + + + + + Эффект звёзд + + + +
+ + + + + + + +``` + +Альтернативно, используя отдельный пакет пресета: + +```html + + + + +``` + +--- + +## Пользовательская конфигурация + +Создайте конфигурацию с нуля с градиентным фоном, интерактивными эффектами при наведении и несколькими типами форм, используя пакет slim. + +```html + + + + + + Пользовательская конфигурация + + + +

Пользовательская конфигурация

+
+ + + + + + +``` + +--- + +## Несколько контейнеров + +Запустите несколько независимых экземпляров частиц на одной странице, каждый со своей конфигурацией. + +```html + + + + + + Несколько контейнеров + + + +
+
+
+
+ + + + + + +``` + +--- + +## Динамическое управление + +Программно запускайте, останавливайте, приостанавливайте и переключайте темы во время выполнения. + +```html + + + + + + Динамическое управление + + + +
+
+ + + + + + +
+ + + + + + +``` + +--- + +Теперь вы ознакомились со всеми основными шаблонами интеграции Vanilla JS для tsParticles v4. Каждый пример представляет собой отдельный HTML-файл, который можно открыть в браузере, чтобы увидеть tsParticles в действии. diff --git a/websites/website/docs/ru/guides/vue3.md b/websites/website/docs/ru/guides/vue3.md new file mode 100644 index 00000000000..bc1e7744ffd --- /dev/null +++ b/websites/website/docs/ru/guides/vue3.md @@ -0,0 +1,622 @@ +--- +title: Интеграция с Vue 3 +description: Пошаговое руководство по интеграции tsParticles в приложения Vue 3 с использованием @tsparticles/vue3. +--- + +# Интеграция с Vue 3 + +Пакет `@tsparticles/vue3` предоставляет нативный компонент Vue 3 и систему плагинов для tsParticles. Это руководство охватывает всё, от базовой настройки до продвинутых паттернов, таких как динамическое переключение тем и пользовательские пресеты. + +--- + +## Установка + +```bash +npm install @tsparticles/vue3 @tsparticles/engine +``` + +Опционально установите пресет или полную сборку: + +```bash +# Полная сборка (все функции) +npm install tsparticles + +# Конкретные пресеты +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars + +# Утилитарные конфиги +npm install @tsparticles/configs +``` + +--- + +## Базовое использование + +Зарегистрируйте плагин в точке входа вашего приложения, затем используйте компонент `` в любом месте. + +### Точка входа (`main.ts`) + +```typescript +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +const app = createApp(App); + +app.use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, +}); + +app.mount("#app"); +``` + +### Компонент (`App.vue`) + +```vue + + + +``` + +--- + +## Использование `particlesInit` с компонентом + +Если вы предпочитаете не использовать глобальный плагин, передайте колбэк `init` напрямую: + +```vue + + + +``` + +--- + +## События + +Компонент генерирует несколько событий жизненного цикла: + +```vue + + + +``` + +--- + +## Эффект конфетти + +Используйте пресет конфетти для праздников: + +```bash +npm install @tsparticles/preset-confetti +``` + +```vue + + + +``` + +Для одноразового взрыва загрузите пресет, затем вызовите `tsParticles.load()` программно внутри метода. + +--- + +## Эффект фейерверка + +Пресет фейерверка создаёт зрелищные взрывы частиц: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```vue + + + +``` + +> **Совет:** Пресет фейерверка требует много ресурсов. Запускайте его по взаимодействию пользователя (например, по клику на кнопку), переключая `v-if`, привязанный к компоненту. + +--- + +## Эффект снега + +Симулируйте падение снега с помощью пресета snow: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +--- + +## Интерактивные частицы + +Добавьте режимы взаимодействия при наведении и клике: + +```vue + + + +``` + +Доступные режимы взаимодействия: `grab`, `repulse`, `bubble`, `connect`, `push`, `remove`, `trail`, `attract`, `light`. + +--- + +## Переключение темы + +Динамически меняйте темы частиц во время выполнения, обновляя реактивный объект опций: + +```vue + + + +``` + +Альтернативно, используйте встроенную опцию [themes](https://particles.js.org/docs/interfaces/Options_Interfaces_IOptions.IOptions.html#themes) и свойство `theme` на контейнере для переключения без конфигурации. + +--- + +## Пользовательский пресет из @tsparticles/configs + +Пакет `@tsparticles/configs` экспортирует готовые объекты конфигурации: + +```bash +npm install @tsparticles/configs +``` + +```vue + + + +``` + +Просмотрите доступные конфиги в пакете `@tsparticles/configs` для готовых к использованию макетов. + +--- + +## Подходы к инициализации движка + +Есть два способа инициализировать движок: + +### 1. Глобальный плагин (рекомендуется) + +```typescript +// main.ts +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +createApp(App) + .use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, + }) + .mount("#app"); +``` + +Затем движок доступен глобально, и все экземпляры `` используют его. + +### 2. Инициализация на уровне компонента + +Передайте колбэк `:init` каждому экземпляру ``. Полезно, когда разным компонентам нужны разные наборы плагинов: + +```vue + +``` + +### 3. Particles Provider (Composition API) + +Используйте провайдер для программного доступа к движку: + +```vue + +``` + +--- + +## Именованные экспорты + TypeScript + +Полный пример TypeScript со всеми частями вместе: + +```vue + + + +``` + +--- + +## Справочник API + +| Проп | Тип | По умолчанию | Описание | +| --------- | ----------------------------------- | --------------- | ----------------------------- | +| `id` | `string` | `"tsparticles"` | ID элемента canvas | +| `options` | `ISourceOptions` | `{}` | Конфигурация частиц | +| `init` | `(engine: Engine) => Promise` | — | Колбэк инициализации движка | +| `url` | `string` | — | URL для загрузки JSON конфиг. | + +| Событие | Полезные данные | Описание | +| ------------------- | --------------- | ----------------------------------------------- | +| `@particles-loaded` | `Container` | Срабатывает при полной инициализации контейнера | +| `@particles-init` | `Engine` | Срабатывает после инициализации движка | + +--- + +## Устранение неполадок + +- **Ошибка: `tsparticles is not defined`** — Убедитесь, что `tsparticles` (или необходимые пресеты) загружены внутри колбэка `init` до рендеринга компонента. +- **Canvas не отображается** — Проверьте, что родительский контейнер имеет ненулевую высоту. Добавьте CSS-правило, например, `#tsparticles { height: 100vh; }`. +- **Проблемы производительности** — Снизьте `fpsLimit`, уменьшите `particles.number.value` или отключите `detectRetina` на маломощных устройствах. +- **SSR (Nuxt)** — Компонент `` только для клиента. Оберните его в `` или используйте директиву `client:only`. diff --git a/websites/website/docs/ru/guides/webcomponents.md b/websites/website/docs/ru/guides/webcomponents.md new file mode 100644 index 00000000000..f3d5e8c1509 --- /dev/null +++ b/websites/website/docs/ru/guides/webcomponents.md @@ -0,0 +1,359 @@ +# Web Components + +Используйте tsParticles с нативными веб-компонентами через пакет `@tsparticles/webcomponents`. Этот подход не требует фреймворка — только чистый JavaScript и пользовательские элементы. + +## Установка + +### Через CDN + +Подключите ядро tsParticles и сборку веб-компонентов: + +```html + + +``` + +### Через npm + сборка + +```bash +npm install @tsparticles/webcomponents tsparticles +``` + +Затем импортируйте в ваш JavaScript-бандл: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; +``` + +## Инициализация движка + +Перед тем как элемент `` сможет рендериться, движок должен быть инициализирован с необходимыми функциями. Вызовите `initParticlesEngine` с колбэком, который загружает нужные плагины: + +```javascript +import { initParticlesEngine } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +> **Зачем `loadFull`?** Он регистрирует все встроенные формы (круг, квадрат, многоугольник, изображение и т.д.), взаимодействия (наведение, клик) и обновления (прозрачность, размер, цвет и т.д.). Для меньшей сборки используйте `tsparticles-slim` или выбирайте отдельные плагины. + +## Определение пользовательского элемента + +После инициализации движка зарегистрируйте пользовательский элемент ``: + +```javascript +import { defineParticlesElement } from "@tsparticles/webcomponents"; + +defineParticlesElement(); +``` + +Это регистрирует тег `web-particles` в `CustomElementRegistry` браузера. Безопасно вызывать несколько раз — дублирующие регистрации игнорируются. + +## Базовое использование + +После выполнения `initParticlesEngine` и `defineParticlesElement` используйте элемент напрямую в HTML: + +```html + + + + + + tsParticles Web Components + + + + + + + +``` + +## Пользовательская конфигурация + +Элемент `` принимает конфигурацию через свойство `options` (объект JavaScript) или через JSON в атрибуте `options`. + +### Через JavaScript-свойство + +```javascript +const el = document.querySelector("web-particles"); +el.options = { + background: { color: "#000000" }, + fpsLimit: 60, + particles: { + color: { value: ["#ff0000", "#00ff00", "#0000ff"] }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { value: 60 }, + opacity: { value: 0.6 }, + shape: { type: ["circle", "square"] }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + repulse: { distance: 200 }, + push: { quantity: 4 }, + }, + }, +}; +``` + +### Через HTML-атрибут (JSON) + +```html + +``` + +> При использовании атрибута `options` значение должно быть валидным JSON. Для сложных конфигураций предпочтительнее присваивание свойства. + +## Динамическое создание + +Вы можете создавать элементы `` полностью в JavaScript и добавлять их в DOM в любое время: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +defineParticlesElement(); + +function createParticles(container, config) { + const el = document.createElement("web-particles"); + el.id = "dynamic-particles"; + el.style.position = "absolute"; + el.style.width = "100%"; + el.style.height = "100%"; + el.style.top = "0"; + el.style.left = "0"; + el.options = config; + container.appendChild(el); + return el; +} + +// Использование +const particles = createParticles(document.body, { + background: { color: "#1a1a2e" }, + particles: { + number: { value: 100 }, + links: { enable: true, color: "#e94560" }, + move: { enable: true, speed: 1 }, + }, +}); +``` + +## Расширение пользовательского элемента + +Вы можете создать подкласс `ParticlesElement` для создания собственного пользовательского элемента со встроенной конфигурацией: + +```javascript +import { initParticlesEngine, ParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +class MyParticlesBackground extends ParticlesElement { + constructor() { + super(); + this.style.position = "fixed"; + this.style.top = "0"; + this.style.left = "0"; + this.style.width = "100%"; + this.style.height = "100%"; + this.style.zIndex = "-1"; + } + + connectedCallback() { + this.options = { + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true, speed: 2 }, + }, + }; + super.connectedCallback(); + } +} + +customElements.define("my-particles-bg", MyParticlesBackground); +``` + +Использование: + +```html + +``` + +## Доступ к контейнеру и управление + +Пользовательский элемент предоставляет экземпляр `Container` tsParticles для императивного управления: + +```javascript +const el = document.querySelector("web-particles"); + +// Доступ к контейнеру (доступен после connectedCallback) +const container = el.container; +container?.pause(); +container?.play(); + +// Уничтожение и очистка +el.dispose(); +``` + +## Полный пример + +Полная HTML-страница с использованием модуля веб-компонентов через CDN-скрипты: + +```html + + + + + + tsParticles Web Components Демо + + + +
+

tsParticles + Web Components

+

Нативные пользовательские элементы, фреймворк не требуется.

+
+ + + + + + +``` + +## Справочник API + +| Экспорт / Свойство | Тип | Описание | +| ------------------------------- | ------------------------ | --------------------------------------------------------- | +| `initParticlesEngine(callback)` | `function` | Инициализация движка tsParticles с загрузчиками плагинов | +| `defineParticlesElement()` | `function` | Регистрация пользовательского элемента `` | +| `ParticlesElement` | `class` | Базовый класс для расширения пользовательскими элементами | +| `element.options` | `ISourceOptions` | Получить/установить объект конфигурации частиц | +| `element.container` | `Container \| undefined` | Ссылка только для чтения на базовый `Container` | +| `element.dispose()` | `function` | Уничтожить экземпляр частиц и очистить ресурсы | diff --git a/websites/website/docs/ru/guides/wordpress.md b/websites/website/docs/ru/guides/wordpress.md new file mode 100644 index 00000000000..6dd6fb83a82 --- /dev/null +++ b/websites/website/docs/ru/guides/wordpress.md @@ -0,0 +1,314 @@ +--- +title: WordPress Guide +description: Полное руководство по интеграции tsParticles с WordPress с использованием плагина, блоков, шорткодов и интеграции в тему. +--- + +# WordPress Guide + +## Содержание + +1. [Установка](#установка) +2. [Активация плагина](#активация-плагина) +3. [Использование виджета и блока](#использование-виджета-и-блока) +4. [Использование шорткода](#использование-шорткода) +5. [Конфигурация через PHP-фильтр](#конфигурация-через-php-фильтр) +6. [Пользовательская конфигурация через фильтр](#пользовательская-конфигурация-через-фильтр) +7. [Интеграция в тему](#интеграция-в-тему) + +--- + +## Установка + +Плагин tsParticles для WordPress доступен в каталоге плагинов WordPress. Установите его прямо из панели администратора WordPress. + +### Из панели администратора WordPress + +1. Перейдите в **Плагины → Добавить новый** +2. Найдите "tsParticles" +3. Нажмите **Установить сейчас** на плагине tsParticles +4. Нажмите **Активировать** + +### Ручная установка + +1. Скачайте ZIP-архив плагина из каталога плагинов WordPress или со [страницы релизов](https://github.com/tsparticles/wordpress/releases) +2. Перейдите в **Плагины → Добавить новый → Загрузить плагин** +3. Выберите ZIP-файл и нажмите **Установить сейчас** +4. Нажмите **Активировать** + +--- + +## Активация плагина + +После активации плагин регистрирует: + +- **Блок Gutenberg** с названием "tsParticles", доступный в инсертере блоков +- **Шорткод** `[tsparticles]` для использования в классическом редакторе или пользовательских PHP-шаблонах +- **PHP-фильтр** `tsparticles_options` для разработчиков, чтобы программно внедрять конфигурацию +- Фронтенд-ресурсы (JavaScript и CSS), которые подключаются только при наличии блока или шорткода на странице + +После активации вы можете проверить работу плагина, перейдя в **Настройки → tsParticles** в боковом меню администратора WordPress, где может быть доступна базовая страница настроек в зависимости от версии плагина. + +--- + +## Использование виджета и блока + +Плагин tsParticles добавляет пользовательский блок Gutenberg для редактора блоков (WordPress 5.0+). + +### Добавление блока + +1. Отредактируйте любую запись или страницу с помощью редактора блоков (Gutenberg) +2. Нажмите кнопку **+** (Добавить блок) +3. Найдите "tsParticles" или "Particles" +4. Нажмите на блок **tsParticles**, чтобы вставить его + +### Настройки блока + +После вставки панель инспектора блока (справа) предоставляет настройки: + +- **Container ID** — уникальный HTML ID для контейнера частиц (по умолчанию: `tsparticles`) +- **Width / Height** — задайте явные размеры или используйте полноэкранный режим +- **Z-Index** — управляет наложением относительно другого контента +- **Configuration** — вставьте JSON-объект опций для полной настройки внешнего вида частиц + +Для боковых панелей темы или областей виджетов, не поддерживающих блоки, используйте подход [Шорткод](#использование-шорткода). + +--- + +## Использование шорткода + +Используйте шорткод `[tsparticles]` в классическом редакторе, пользовательских HTML-блоках или напрямую в PHP-файлах шаблонов, чтобы встраивать фон с частицами в любом месте вашего сайта. + +### Базовый шорткод + +``` +[tsparticles] +``` + +Он отображает конфигурацию частиц по умолчанию (простые плавающие круги на тёмном фоне). + +### Шорткод с опциями + +Передайте JSON-конфигурацию напрямую в шорткод, используя атрибут `options`: + +``` +[tsparticles options='{"particles":{"number":{"value":50},"color":{"value":"#ff0000"},"shape":{"type":"circle"},"opacity":{"value":0.5},"size":{"value":{"min":1,"max":3}},"move":{"enable":true,"speed":1,"outModes":{"default":"bounce"}}},"background":{"color":"#1a1a2e"}}'] +``` + +### Шорткод в PHP-шаблонах + +```php +// В header.php или footer.php вашей темы +echo do_shortcode('[tsparticles]'); +``` + +Или с пользовательскими опциями: + +```php +$options = [ + 'particles' => [ + 'number' => ['value' => 80], + 'color' => ['value' => '#00d4ff'], + 'shape' => ['type' => 'circle'], + 'links' => [ + 'enable' => true, + 'distance' => 150, + 'color' => '#00d4ff', + 'opacity' => 0.3, + ], + 'move' => [ + 'enable' => true, + 'speed' => 1.5, + 'outModes' => ['default' => 'bounce'], + ], + ], + 'background' => ['color' => '#0d1117'], +]; + +echo do_shortcode('[tsparticles options=\'' . wp_json_encode($options) . '\']'); +``` + +--- + +## Конфигурация через PHP-фильтр + +Плагин предоставляет фильтр `tsparticles_options`, который позволяет переопределять или расширять конфигурацию частиц из файла `functions.php` вашей темы или пользовательского плагина. Это рекомендуемый подход для разработчиков, поскольку он хранит конфигурацию в PHP и избегает встроенного JSON. + +### Базовый фильтр + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + $options['background'] = ['color' => '#0d1117']; + $options['particles']['number']['value'] = 100; + $options['particles']['color']['value'] = '#00d4ff'; + $options['particles']['shape']['type'] = 'circle'; + $options['particles']['opacity']['value'] = 0.6; + $options['particles']['size']['value'] = ['min' => 2, 'max' => 5]; + $options['particles']['links']['enable'] = true; + $options['particles']['links']['distance'] = 150; + $options['particles']['links']['color'] = '#00d4ff'; + $options['particles']['links']['opacity'] = 0.3; + $options['particles']['move']['enable'] = true; + $options['particles']['move']['speed'] = 1.5; + $options['particles']['move']['outModes']['default'] = 'bounce'; + return $options; +}); +``` + +Этот фильтр выполняется перед рендерингом шорткода или блока, поэтому любой экземпляр tsParticles на странице получает настроенную конфигурацию. + +--- + +## Пользовательская конфигурация через фильтр + +Вот полная пользовательская конфигурация, демонстрирующая всю мощь фильтра — включая интерактивность, несколько типов форм и поддержку тем. + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + + // Полноэкранный фон + $options['fullScreen'] = [ + 'enable' => true, + 'zIndex' => -1, + ]; + + $options['fpsLimit'] = 60; + + // Настройки частиц + $options['particles'] = [ + 'number' => [ + 'value' => 60, + 'density' => ['enable' => true, 'width' => 800, 'height' => 800], + ], + 'color' => [ + 'value' => ['#ff6b6b', '#feca57', '#48dbfb', '#ff9ff3', '#54a0ff'], + ], + 'shape' => [ + 'type' => ['circle', 'triangle', 'polygon'], + 'options' => [ + 'polygon' => ['sides' => 6], + ], + ], + 'opacity' => [ + 'value' => ['min' => 0.4, 'max' => 0.8], + ], + 'size' => [ + 'value' => ['min' => 3, 'max' => 8], + ], + 'links' => [ + 'enable' => true, + 'distance' => 200, + 'color' => '#ffffff', + 'opacity' => 0.15, + 'width' => 1, + ], + 'move' => [ + 'enable' => true, + 'speed' => 2, + 'direction' => 'none', + 'random' => true, + 'straight' => false, + 'outModes' => ['default' => 'out'], + ], + ]; + + // Интерактивность + $options['interactivity'] = [ + 'events' => [ + 'onHover' => ['enable' => true, 'mode' => 'attract'], + 'onClick' => ['enable' => true, 'mode' => 'repulse'], + ], + 'modes' => [ + 'attract' => ['distance' => 200, 'duration' => 0.4, 'factor' => 1], + 'repulse' => ['distance' => 200, 'duration' => 0.4], + ], + ]; + + // Фон + $options['background'] = [ + 'color' => '#0f0f23', + ]; + + // Поддержка тем — переключение светлого режима + $options['themes'] = [ + [ + 'name' => 'light', + 'default' => ['value' => false], + 'options' => [ + 'background' => ['color' => '#f0f0f5'], + 'particles' => [ + 'color' => ['value' => ['#e74c3c', '#2ecc71', '#3498db', '#f1c40f']], + 'links' => ['color' => '#333333', 'opacity' => 0.2], + ], + ], + ], + ]; + + return $options; +}); +``` + +--- + +## Интеграция в тему + +Чтобы сделать tsParticles постоянным фоном во всей вашей теме WordPress, добавьте шорткод или прямой PHP-вызов в `header.php` или `footer.php` вашей темы. + +### Фон в шапке + +```php + + +
+ +
+ +``` + +### Стили для полноэкранного фона + +Добавьте следующий CSS в `style.css` вашей темы или через `wp_add_inline_style`: + +```css +#tsparticles-background { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + z-index: -1; + pointer-events: none; +} + +/* Убедитесь, что контент отображается поверх частиц */ +.site-content { + position: relative; + z-index: 1; +} +``` + +### Условная загрузка + +Чтобы загружать tsParticles только на определённых страницах: + +```php +// В functions.php — подключение только на главной странице +add_action('wp', function () { + if (is_front_page()) { + add_filter('tsparticles_options', function (array $options): array { + $options['particles']['number']['value'] = 120; + $options['particles']['color']['value'] = '#ffffff'; + $options['particles']['move']['speed'] = 0.8; + $options['background']['color'] = '#1a1a2e'; + return $options; + }); + } +}); +``` + +Комбинируйте это с размещением блока или шорткода для производительного фона с частицами на конкретных страницах. + +--- + +Теперь у вас есть всё необходимое для интеграции tsParticles в сайт WordPress. Предпочитаете ли вы редактор блоков, шорткоды или полный PHP-контроль — каждый подход даёт уникальный фон с частицами с минимальными усилиями. diff --git a/websites/website/docs/zh/guide/bundles-all.md b/websites/website/docs/zh/guide/bundles-all.md index 3188819e880..919aa083c22 100644 --- a/websites/website/docs/zh/guide/bundles-all.md +++ b/websites/website/docs/zh/guide/bundles-all.md @@ -1,21 +1,42 @@ -# Bundle: All +# 捆绑包:All -`@tsparticles/all` 会加载全部官方功能,适合快速原型阶段。 +`@tsparticles/all` 加载 tsParticles 仓库中的**所有内容**:每种形状、交互、更新器、效果、路径、缓动、插件和导出。它是体积最大的捆绑包,适用于原型设计和演示。 -## 何时选择 All +## 包含的功能 -- 你希望立即获得全部功能。 -- 你在快速试验不同配置。 -- 你更在意接入速度而非 bundle 体积。 +继承 `tsparticles`(full)的全部功能,外加: + +**所有形状:** 箭头、扑克花色、齿轮、心形、无穷、矩阵、路径、丝带、圆角多边形、圆角矩形、螺旋、圆方角形 + +**所有外部交互:** cannon、light、particle、pop、particles-repulse + +**所有效果:** 气泡、滤镜、粒子、阴影、拖尾 + +**所有路径生成器:** branches、brownian、curl-noise、curves、fractal-noise、grid、levy、perlin-noise、polygon、random、simplex-noise、spiral、svg、zig-zag + +**所有缓动:** back、bounce、circ、cubic、elastic、expo、gaussian、linear、quad、quart、quint、sigmoid、sine、smoothstep + +**所有颜色插件:** HEX、HSL、RGB、HSV、HWB、LAB、LCH、Named、OKLAB、OKLCH + +**所有插件:** absorbers、background-mask、canvas-mask、emitters(所有形状)、easings(所有)、export-image、export-json、export-video、infection、manual-particles、motion、poisson-disc、polygon-mask、responsive、sounds、themes、trail、zoom + +**所有更新器:** destroy、gradient、life、opacity、orbit、out-modes、paint、roll、rotate、size、tilt、twinkle、wobble + +## 何时使用 + +- 快速原型设计以探索可能性 +- 演示和展示 +- 不关心大小的开发环境 +- **不推荐用于生产环境**——优先选择更有针对性的捆绑包 ## 安装 +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/all ``` -## Setup example - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadAll } from "@tsparticles/all"; @@ -25,20 +46,48 @@ await loadAll(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { number: { value: 100 }, + shape: { type: "heart" }, move: { enable: true, speed: 2 }, }, }, }); ``` -## 常见问题 +### CDN(script 标签) + +```html + + + +``` + +## `tsparticles` 与 `@tsparticles/all` 的区别 + +详情请参见 [bundles-full 页面](/zh/guide/bundles-full)的比较表格。 + +## 常见错误 -- 在生产环境中使用 all,而不是更精简的目标 bundle。 -- 在 `loadAll(...)` 之前调用 `tsParticles.load(...)`。 +- 在生产环境中使用——优先选择 `@tsparticles/slim` 或 `tsparticles` 以获得更小的捆绑包。 +- 在 `loadAll(tsParticles)` 之前调用 `tsParticles.load()`。 -## 相关页面 +## 参见 -- 概览: [`/guide/bundles`](/zh/guide/bundles) -- 安装矩阵: [`/guide/installation`](/zh/guide/installation) +- [捆绑包概览](/zh/guide/bundles) +- [安装指南](/zh/guide/installation) diff --git a/websites/website/docs/zh/guide/bundles-basic.md b/websites/website/docs/zh/guide/bundles-basic.md index cf7bb5af6ef..014fb9b5e0e 100644 --- a/websites/website/docs/zh/guide/bundles-basic.md +++ b/websites/website/docs/zh/guide/bundles-basic.md @@ -1,21 +1,46 @@ -# Bundle: Basic +# 捆绑包:Basic -`@tsparticles/basic` 适合极简轻量场景,运行时开销更低。 +`@tsparticles/basic` 是最轻量的捆绑包。仅包含基本要素:可移动的圆形,以及可动画的透明度和大小。 -## 何时选择 Basic +## 包含的功能 -- bundle 体积是首要目标。 -- 你只需要核心基础效果。 -- 不需要高级 plugins。 +**形状:** 圆形 + +**更新器:** + +- paint(颜色) +- opacity(透明度) +- out-modes(离开屏幕时的行为) +- size(大小) + +**插件:** + +- move(移动) +- blend(颜色混合) +- HEX、HSL、RGB 颜色插件 + +**不包含:** + +- 鼠标/触摸交互 +- 粒子连线 +- 其他形状(方形、星形、图片、多边形等) +- 发射器、吸收器、声音 +- 旋转、生命周期、滚动、倾斜、摆动 + +## 何时使用 + +- 捆绑包大小是你的首要关注点 +- 你只需要点移动的效果 +- 不需要交互或复杂形状 ## 安装 +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/basic ``` -## Setup example - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadBasic } from "@tsparticles/basic"; @@ -25,20 +50,48 @@ await loadBasic(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#ffffff" }, particles: { number: { value: 50 }, - move: { enable: true, speed: 1.5 }, + color: { value: ["#5bc0eb", "#fde74c", "#9bc53d"] }, + size: { + value: { min: 300, max: 400 }, + animation: { enable: true, speed: 100 }, + }, + move: { enable: true, speed: 10 }, }, }, }); ``` -## 常见问题 +### CDN(script 标签) + +```html + + + +``` + +## 常见错误 -- 期待 basic 不包含的 plugin 功能。 -- 在 `loadBasic(...)` 之前调用 `tsParticles.load(...)`。 +- 期望不包含的功能(例如 `links`、鼠标交互)——这些需要更高级的捆绑包。 +- 在 `loadBasic(tsParticles)` 之前调用 `tsParticles.load()`——形状和更新器尚未注册。 +- 只安装 `@tsparticles/engine` 而不安装捆绑包——引擎本身不绘制任何内容。 -## 相关页面 +## 参见 -- 概览: [`/guide/bundles`](/zh/guide/bundles) -- 安装矩阵: [`/guide/installation`](/zh/guide/installation) +- [捆绑包概览](/zh/guide/bundles) +- [安装指南](/zh/guide/installation) diff --git a/websites/website/docs/zh/guide/bundles-confetti.md b/websites/website/docs/zh/guide/bundles-confetti.md index 22f0e4f7d8b..2715cae3fc2 100644 --- a/websites/website/docs/zh/guide/bundles-confetti.md +++ b/websites/website/docs/zh/guide/bundles-confetti.md @@ -1,42 +1,83 @@ -# Bundle: Confetti +# 捆绑包:Confetti -`@tsparticles/confetti` 提供面向彩纸效果的聚焦 API,接入成本很低。 +`@tsparticles/confetti` 提供了简化的 API,只需一次函数调用即可创建彩纸效果。无需直接操作 `tsParticles`。 -## 何时选择 Confetti +## 包含的功能 -- 你需要一键触发的庆祝效果。 -- 你不需要手动连接 engine。 -- 你希望在 UI 事件里用紧凑 API 快速触发。 +**形状:** 圆形、心形、扑克花色(红心、方块、梅花、黑桃)、emoji、图片、多边形、方形、星形 + +**内部插件:** emitters(发射器)、motion(尊重用户减少动效的偏好) + +**更新器:** life(生命周期)、roll(滚动)、rotate(旋转)、tilt(倾斜)、wobble(摆动) + +**API:** `confetti(options)` 或 `confetti(canvasId, options)` + +## 何时使用 + +- "恭喜!"或"生日快乐!"按钮 +- 快速庆祝效果 +- 你不想手动配置引擎 ## 安装 +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/confetti ``` -## Setup example - ```ts import { confetti } from "@tsparticles/confetti"; +// 基本效果 await confetti({ - count: 80, - spread: 60, + particleCount: 100, + spread: 70, + origin: { x: 0.5, y: 0.5 }, }); -await confetti("canvas-id", { - count: 50, +// 在特定 canvas 上 +await confetti("my-canvas-id", { + particleCount: 50, angle: 90, spread: 45, + colors: ["#ff0000", "#00ff00", "#0000ff"], }); ``` -## 常见问题 +### CDN(script 标签) + +```html + + +``` + +### 主要参数 + +| 参数 | 类型 | 默认值 | 描述 | +| --------------- | -------- | ------------ | -------------------------------------------------- | +| `particleCount` | number | 50 | 彩纸数量 | +| `spread` | number | 60 | 扩散角度(度) | +| `angle` | number | 90 | 方向(度,90 = 向下) | +| `startVelocity` | number | 30 | 初始速度 | +| `colors` | string[] | — | 彩纸颜色 | +| `origin` | { x, y } | { 0.5, 0.5 } | 原点(0-1) | +| `drift` | number | 0 | 水平漂移 | +| `shapes` | string[] | — | 形状:"circle"、"heart"、"square"、"star"、"cards" | + +## 常见错误 -- 误以为 `@tsparticles/confetti` 会导出 `tsParticles`。 -- 无意间复用同一个 canvas id。 +- 误以为 `@tsparticles/confetti` 会导出 `tsParticles`——它不会。 +- 无意间重复使用同一个 canvas ID。 +- 在循环中调用 `confetti` 而不考虑性能——使用合理的间隔,或在动画完成后停止。 -## 相关页面 +## 参见 -- 概览: [`/guide/bundles`](/zh/guide/bundles) -- Playground bundles: [`/playground/bundles`](/zh/playground/bundles) +- [捆绑包概览](/zh/guide/bundles) +- [烟花捆绑包](/zh/guide/bundles-fireworks) diff --git a/websites/website/docs/zh/guide/bundles-fireworks.md b/websites/website/docs/zh/guide/bundles-fireworks.md index ba4e10117c1..2bdbb18aa4c 100644 --- a/websites/website/docs/zh/guide/bundles-fireworks.md +++ b/websites/website/docs/zh/guide/bundles-fireworks.md @@ -1,44 +1,81 @@ -# Bundle: Fireworks +# 捆绑包:Fireworks -`@tsparticles/fireworks` 提供面向烟花效果的聚焦 API,适合快速接入。 +`@tsparticles/fireworks` 提供了简化的 API,只需一次函数调用即可创建烟花效果。支持声音、自定义颜色和实例控制(暂停/播放)。 -## 何时选择 Fireworks +## 包含的功能 -- 你需要一键触发的烟花动画。 -- 你不需要直接 wiring engine。 -- 你想在庆祝场景中使用紧凑 API。 +**形状:** 线条、圆形(来自 basic) + +**内部插件:** emitters(发射器)、emitters-shape-square(方形发射器)、blend(混合)、sounds(声音) + +**更新器:** destroy(销毁)、life(生命周期)、paint(绘制)、rotate(旋转) + +**API:** `fireworks(options)`——返回一个可控制的实例 + +## 何时使用 + +- 新年或庆祝效果 +- 庆祝 UI +- 你不想手动配置引擎 ## 安装 +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/fireworks ``` -## Setup example - ```ts import { fireworks } from "@tsparticles/fireworks"; +// 基本效果 const instance = await fireworks({ - colors: ["#ffffff", "#ff0000"], - sounds: false, + colors: ["#ffffff", "#ff0000", "#00ff00", "#0000ff"], + sounds: true, }); +// 实例控制 instance?.pause(); instance?.play(); -await fireworks("canvas-id", { +// 在特定 canvas 上 +await fireworks("my-canvas", { rate: 3, speed: { min: 10, max: 25 }, + sounds: false, }); ``` -## 常见问题 +### CDN(script 标签) + +```html + + +``` + +### 主要参数 + +| 参数 | 类型 | 默认值 | 描述 | +| ------------ | ------------ | ------ | --------------- | +| `colors` | string[] | — | 爆炸颜色 | +| `rate` | number | — | 每秒烟花数 | +| `speed` | { min, max } | — | 粒子速度 | +| `sounds` | boolean | true | 启用音效 | +| `gravity` | number | — | 重力(默认:0) | +| `opacity` | number | — | 不透明度(0-1) | +| `brightness` | { min, max } | — | 爆炸亮度 | + +## 常见错误 -- 误以为 `@tsparticles/fireworks` 会导出 `tsParticles`。 -- 多次调用 `fireworks(...)` 却不管理返回的 instance。 +- 误以为 `@tsparticles/fireworks` 会导出 `tsParticles`——它不会。 +- 在循环中调用 `fireworks()` 而不管理实例——该效果本身就是持续进行的。 +- 离开页面时没有停止实例——调用 `instance?.pause()` 或 `instance?.stop()`。 -## 相关页面 +## 参见 -- 概览: [`/guide/bundles`](/zh/guide/bundles) -- Playground bundles: [`/playground/bundles`](/zh/playground/bundles) +- [捆绑包概览](/zh/guide/bundles) +- [彩纸捆绑包](/zh/guide/bundles-confetti) diff --git a/websites/website/docs/zh/guide/bundles-full.md b/websites/website/docs/zh/guide/bundles-full.md index 6122a98e511..994ce28da8e 100644 --- a/websites/website/docs/zh/guide/bundles-full.md +++ b/websites/website/docs/zh/guide/bundles-full.md @@ -1,21 +1,48 @@ -# Bundle: tsparticles (Full) +# 捆绑包:tsparticles(Full) -`tsparticles` 是 full bundle,用一个 loader 就能加载大量官方功能。 +`tsparticles`(npm:`tsparticles`,加载器:`loadFull`)是官方的完整捆绑包。包含 Slim 的所有功能,加上发射器、吸收器、文本形状和高级动画(摆动、滚动、倾斜、闪烁、销毁)。 -## 何时选择 tsparticles (Full) +## 包含的功能 -- 你需要大量官方功能,但不想手动挑选 plugins。 -- 你希望先有一套可用于 production 的完整基础,再做细化。 -- 你希望通过 `tsParticles` API 直接控制 engine。 +继承 `@tsparticles/slim` 的全部功能,外加: + +**额外的形状:** 文本(支持自定义字体) + +**额外的外部交互:** + +- drag(用鼠标拖拽粒子) +- trail(鼠标后的粒子拖尾) + +**额外的更新器:** + +- destroy(粒子销毁动画) +- roll(滚动) +- tilt(3D 倾斜) +- twinkle(间歇闪烁) +- wobble(摆动) + +**插件:** + +- absorbers(吸收粒子黑洞) +- emitters(持续粒子源) +- emitters-shape-circle、emitters-shape-square(发射器形状) + +## 何时使用 + +- 需要发射器(持续生成粒子) +- 需要吸收器(吸收粒子) +- 需要带有自定义字体的文本形状 +- 需要高级动画(摆动、倾斜、滚动、闪烁) +- 在使用单个插件之前的良好过渡选择 ## 安装 +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine tsparticles ``` -## Setup 示例 - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadFull } from "tsparticles"; @@ -25,20 +52,65 @@ await loadFull(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#000" }, particles: { - number: { value: 100 }, - move: { enable: true, speed: 2 }, + number: { value: 50 }, + shape: { type: "text", options: { text: ["🔥", "✨", "⭐"] } }, + size: { value: 24 }, + move: { enable: true, speed: 1 }, + wobble: { enable: true, distance: 10 }, + }, + emitters: { + direction: "top", + rate: { quantity: 2, delay: 0.3 }, }, }, }); ``` -## 常见问题 +### CDN(script 标签) + +```html + + + +``` + +## `tsparticles` 与 `@tsparticles/all` 的区别 + +| 方面 | `tsparticles`(full) | `@tsparticles/all` | +| -------- | ------------------------------------------------- | ---------------------------------------------------------------- | +| 大小 | 适中 | 非常大 | +| 形状 | 圆形、方形、星形、多边形、线条、图片、emoji、文本 | 所有形状(心形、扑克花色、箭头、螺旋、齿轮、圆角矩形等) | +| 交互 | Slim + drag + trail | 全部(cannon、light、pop、particle、repulse) | +| 路径 | 仅 Quad 缓动 | 14 种路径生成器 | +| 效果 | 无 | 5 种效果(气泡、滤镜、阴影等) | +| 导出 | 无 | 图片、JSON、视频 | +| 额外插件 | absorbers、emitters | 全部(声音、主题、拖尾、缩放、多边形遮罩、画布遮罩、背景遮罩等) | +| 缓动 | Quad | 15 种缓动 | + +## 常见错误 -- 在 `loadFull(...)` 之前调用 `tsParticles.load(...)`。 -- 误以为它和 `@tsparticles/all` 是同一个包(它们是不同 bundles)。 +- 混淆 `tsparticles` 和 `@tsparticles/all`——它们是不同的包。 +- 在 `loadFull(tsParticles)` 之前调用 `tsParticles.load()`。 +- npm 包名是 `tsparticles`(不是 `@tsparticles/full`),加载器是 `loadFull`。 -## 相关页面 +## 参见 -- 总览: [`/guide/bundles`](/zh/guide/bundles) -- 安装矩阵: [`/guide/installation`](/zh/guide/installation) +- [捆绑包概览](/zh/guide/bundles) +- [安装指南](/zh/guide/installation) diff --git a/websites/website/docs/zh/guide/bundles-particles.md b/websites/website/docs/zh/guide/bundles-particles.md index 532ee940b95..80ec1ecacae 100644 --- a/websites/website/docs/zh/guide/bundles-particles.md +++ b/websites/website/docs/zh/guide/bundles-particles.md @@ -1,42 +1,98 @@ -# Bundle: Particles +# 捆绑包:Particles -`@tsparticles/particles` 提供面向简单粒子背景的聚焦 API。 +`@tsparticles/particles` 提供了用于创建交互式粒子背景的简化 API。是 `@tsparticles/basic` 的更好替代方案,具有专用 API 而无需手动配置引擎。 -## 何时选择 Particles +## 包含的功能 -- 你想快速接入粒子背景。 -- 你不想手动配置 engine/plugins。 -- 你偏好紧凑的应用式 API。 +**形状:** 圆形(来自 basic) + +**内部插件:** interactivity(交互,包含 links 和 collisions) + +**交互:** links(粒子连线)、collisions(碰撞) + +**API:** `particles(options)` 或 `particles(canvasId, options)` + +## 何时使用 + +- 网站粒子背景 +- 带有粒子连线(节点式效果)的背景 +- 你不想手动配置引擎 ## 安装 +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/particles ``` -## Setup example - ```ts import { particles } from "@tsparticles/particles"; +// 带连线的背景 await particles({ count: 120, links: true, - linksColor: "#0ff", + color: "#ffffff", + linksColor: "#00d8ff", + radius: 3, + speed: 2, + opacity: 0.8, }); -await particles("canvas-id", { +// 在特定 canvas 上 +await particles("my-canvas", { count: 80, shape: ["circle", "square"], + links: true, }); + +// 自定义颜色 +await particles({ + count: 100, + color: ["#ff6b6b", "#4ecdc4", "#45b7d1"], + links: false, +}); +``` + +### CDN(script 标签) + +```html + + ``` -## 常见问题 +### 主要参数 + +| 参数 | 类型 | 默认值 | 描述 | +| ------------ | ------------------ | ---------- | --------------- | +| `count` | number | 50 | 粒子数量 | +| `radius` | number | 3 | 粒子半径 | +| `speed` | number | 2 | 移动速度 | +| `opacity` | number | 0.8 | 不透明度(0-1) | +| `color` | string \| string[] | "#ffffff" | 粒子颜色 | +| `links` | boolean | false | 显示连线 | +| `linksColor` | string | "#ffffff" | 连线颜色 | +| `linksWidth` | number | 1 | 连线粗细 | +| `shape` | string[] | ["circle"] | 粒子形状 | + +## 常见错误 -- 误以为 `@tsparticles/particles` 会导出 `tsParticles`。 -- 无意间复用同一个 canvas id。 +- 误以为 `@tsparticles/particles` 会导出 `tsParticles`——它不会。 +- 无意间重复使用同一个 canvas ID。 +- 期望高级形状(星形、多边形)——particles 捆绑包基于 basic,仅使用圆形。 -## 相关页面 +## 参见 -- 概览: [`/guide/bundles`](/zh/guide/bundles) -- Playground bundles: [`/playground/bundles`](/zh/playground/bundles) +- [捆绑包概览](/zh/guide/bundles) +- [开始使用](/zh/guide/getting-started) diff --git a/websites/website/docs/zh/guide/bundles-slim.md b/websites/website/docs/zh/guide/bundles-slim.md index a8e08a7b5db..d11ce2c1c5c 100644 --- a/websites/website/docs/zh/guide/bundles-slim.md +++ b/websites/website/docs/zh/guide/bundles-slim.md @@ -1,21 +1,61 @@ -# Bundle: Slim +# 捆绑包:Slim -`@tsparticles/slim` 是大多数项目的推荐默认选择。 +`@tsparticles/slim` 是大多数项目的推荐捆绑包。包含现代粒子动画所需的一切,具备鼠标交互、多种形状和粒子连线功能。 -## 何时选择 Slim +## 包含的功能 -- 你需要体积与功能的平衡。 -- 你直接使用 `tsParticles` engine API。 -- 你需要常用 shape/interactions,但不想加载全部能力。 +继承 `@tsparticles/basic` 的全部功能,外加: + +**形状:** 圆形、方形、星形、多边形、线条、图片、emoji + +**外部交互(鼠标/触摸):** + +- attract(吸引) +- bounce(弹跳) +- bubble(气泡) +- connect(连接) +- destroy(销毁) +- grab(抓取) +- parallax(视差) +- pause(暂停) +- push(推动) +- remove(移除) +- repulse(排斥) +- slow(减速) + +**粒子交互:** + +- attract(吸引) +- collisions(碰撞) +- links(粒子连线) + +**额外的更新器:** + +- life(生命周期) +- rotate(旋转) + +**插件:** + +- interactivity(交互) +- easing-quad(二次缓动) +- HEX、HSL、RGB 颜色插件 + +## 何时使用 + +- 推荐作为大多数项目的起点 +- 需要多种形状(圆形、星形、多边形、图片) +- 需要鼠标交互(点击、悬停、气泡、排斥) +- 需要粒子连线 +- 在捆绑包大小和功能之间取得良好平衡 ## 安装 +### npm/pnpm/yarn + ```bash pnpm add @tsparticles/engine @tsparticles/slim ``` -## Setup example - ```ts import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; @@ -25,21 +65,47 @@ await loadSlim(tsParticles); await tsParticles.load({ id: "tsparticles", options: { + background: { color: "#0b1020" }, particles: { number: { value: 80 }, + links: { enable: true, distance: 150 }, move: { enable: true, speed: 2 }, - links: { enable: true }, + shape: { type: ["circle", "star", "square"] }, }, }, }); ``` -## 常见问题 +### CDN(script 标签) + +```html + + + +``` + +## 常见错误 -- 在 `loadSlim(...)` 之前调用 `tsParticles.load(...)`。 -- engine 与 plugins 版本混用。 +- 在 `loadSlim(tsParticles)` 之前调用 `tsParticles.load()`。 +- 引擎和捆绑包版本混用——保持版本一致。 +- 期望更高级捆绑包的功能(发射器、吸收器、文本、摆动)——需要 `tsparticles`(full)或单独的插件。 -## 相关页面 +## 参见 -- 概览: [`/guide/bundles`](/zh/guide/bundles) -- 安装矩阵: [`/guide/installation`](/zh/guide/installation) +- [捆绑包概览](/zh/guide/bundles) +- [安装指南](/zh/guide/installation) diff --git a/websites/website/docs/zh/guide/bundles.md b/websites/website/docs/zh/guide/bundles.md index beed6994944..6d33ae553fb 100644 --- a/websites/website/docs/zh/guide/bundles.md +++ b/websites/website/docs/zh/guide/bundles.md @@ -1,104 +1,184 @@ -# Bundles 指南 - -本页帮助你选择合适的 `tsParticles` bundle,并快速完成 setup。 - -## 包对比 - -| 包 | 适用场景 | setup 方式 | -| ------------------------ | ---------------------------------- | ---------------------------------------------- | -| `@tsparticles/basic` | 超轻量场景 | `tsParticles` + `await loadBasic(tsParticles)` | -| `@tsparticles/slim` | 大多数网站/应用 | `tsParticles` + `await loadSlim(tsParticles)` | -| `tsparticles` | 官方全量能力组合并保留 engine 控制 | `tsParticles` + `await loadFull(tsParticles)` | -| `@tsparticles/all` | 全功能、快速原型 | `tsParticles` + `await loadAll(tsParticles)` | -| `@tsparticles/confetti` | 一次调用的彩纸效果 | `await confetti(options)` | -| `@tsparticles/fireworks` | 一次调用的烟花效果 | `await fireworks(options)` | -| `@tsparticles/particles` | 简化的粒子背景 API | `await particles(options)` | -| `@tsparticles/ribbons` | 一次调用的 ribbons 效果 | `await ribbons(options)` | - -## Bundle 分页指南 - -- Basic: [`/guide/bundles-basic`](/zh/guide/bundles-basic) -- Slim: [`/guide/bundles-slim`](/zh/guide/bundles-slim) -- tsparticles (Full): [`/guide/bundles-full`](/zh/guide/bundles-full) -- All: [`/guide/bundles-all`](/zh/guide/bundles-all) -- Confetti: [`/guide/bundles-confetti`](/zh/guide/bundles-confetti) -- Fireworks: [`/guide/bundles-fireworks`](/zh/guide/bundles-fireworks) -- Particles: [`/guide/bundles-particles`](/zh/guide/bundles-particles) -- Ribbons(demo + docs): [`/demos/recipes/ribbons`](/zh/demos/recipes/ribbons) · - -## 安装 - -按你的使用场景安装对应的包路径。 - -```bash -pnpm add @tsparticles/engine @tsparticles/basic -pnpm add @tsparticles/engine @tsparticles/slim -pnpm add @tsparticles/engine tsparticles -pnpm add @tsparticles/engine @tsparticles/all -pnpm add @tsparticles/confetti -pnpm add @tsparticles/fireworks -pnpm add @tsparticles/particles -pnpm add @tsparticles/ribbons +# 捆绑包指南 + +tsParticles 是模块化的。`@tsparticles/engine` 包只包含核心引擎;要获得可见效果,你必须注册**形状**(绘制什么)、**更新器**(如何动画)、**交互**(如何响应鼠标/触摸)和**插件**(额外功能)。这一切都通过**捆绑包**完成。 + +## 捆绑包分类 + +| 类别 | 捆绑包 | API | +| ------------- | --------------------------------------------------------------------------------------------------- | ---------------------------------------- | +| 引擎 + 加载器 | `@tsparticles/basic`、`@tsparticles/slim`、`tsparticles`、`@tsparticles/all` | `tsParticles.load({ id, options })` | +| 专用 API | `@tsparticles/confetti`、`@tsparticles/fireworks`、`@tsparticles/particles`、`@tsparticles/ribbons` | `confetti({...})`、`fireworks({...})` 等 | + +## 完整功能对比 + +图例:● = 包含,○ = 不包含 + +| 功能 | basic | slim | full (`tsparticles`) | all | +| --------------------------------------------------------------------------------------------------- | ----- | ---- | -------------------- | ---------------- | +| **形状** | | | | | +| 圆形 | ● | ● | ● | ● | +| 方形 | ○ | ● | ● | ● | +| 星形 | ○ | ● | ● | ● | +| 多边形 | ○ | ● | ● | ● | +| 线条 | ○ | ● | ● | ● | +| 图片 | ○ | ● | ● | ● | +| Emoji | ○ | ● | ● | ● | +| 文本 | ○ | ○ | ● | ● | +| 扑克花色 | ○ | ○ | ○ | ● | +| 心形 | ○ | ○ | ○ | ● | +| 箭头 | ○ | ○ | ○ | ● | +| 圆角矩形 | ○ | ○ | ○ | ● | +| 圆角多边形 | ○ | ○ | ○ | ● | +| 螺旋 | ○ | ○ | ○ | ● | +| 圆方角形 | ○ | ○ | ○ | ● | +| 齿轮 | ○ | ○ | ○ | ● | +| 无穷 | ○ | ○ | ○ | ● | +| 矩阵 | ○ | ○ | ○ | ● | +| 路径 | ○ | ○ | ○ | ● | +| 丝带 | ○ | ○ | ○ | ● | +| **外部交互(鼠标/触摸)** | | | | | +| 吸引 | ○ | ● | ● | ● | +| 弹跳 | ○ | ● | ● | ● | +| 气泡 | ○ | ● | ● | ● | +| 连接 | ○ | ● | ● | ● | +| 销毁 | ○ | ● | ● | ● | +| 抓取 | ○ | ● | ● | ● | +| 视差 | ○ | ● | ● | ● | +| 暂停 | ○ | ● | ● | ● | +| 推动 | ○ | ● | ● | ● | +| 移除 | ○ | ● | ● | ● | +| 排斥 | ○ | ● | ● | ● | +| 减速 | ○ | ● | ● | ● | +| 拖拽 | ○ | ○ | ● | ● | +| 拖尾 | ○ | ○ | ● | ● | +| 加农炮 | ○ | ○ | ○ | ● | +| 粒子 | ○ | ○ | ○ | ● | +| 弹出 | ○ | ○ | ○ | ● | +| 灯光 | ○ | ○ | ○ | ● | +| **粒子交互** | | | | | +| 连线 | ○ | ● | ● | ● | +| 碰撞 | ○ | ● | ● | ● | +| 吸引 | ○ | ● | ● | ● | +| 排斥 | ○ | ○ | ○ | ● | +| **更新器(动画)** | | | | | +| 透明度 | ● | ● | ● | ● | +| 大小 | ● | ● | ● | ● | +| 离开模式 | ● | ● | ● | ● | +| 绘制(颜色) | ● | ● | ● | ● | +| 旋转 | ○ | ● | ● | ● | +| 生命周期 | ○ | ● | ● | ● | +| 销毁 | ○ | ○ | ● | ● | +| 滚动 | ○ | ○ | ● | ● | +| 倾斜 | ○ | ○ | ● | ● | +| 闪烁 | ○ | ○ | ● | ● | +| 摆动 | ○ | ○ | ● | ● | +| 渐变 | ○ | ○ | ○ | ● | +| 轨道 | ○ | ○ | ○ | ● | +| **插件** | | | | | +| 移动 | ● | ● | ● | ● | +| 混合 | ● | ● | ● | ● | +| 发射器 | ○ | ○ | ● | ● | +| 吸收器 | ○ | ○ | ● | ● | +| 声音 | ○ | ○ | ○ | ● | +| 动效(用户偏好) | ○ | ○ | ○ | ● | +| 主题 | ○ | ○ | ○ | ● | +| 多边形遮罩 | ○ | ○ | ○ | ● | +| 画布遮罩 | ○ | ○ | ○ | ● | +| 背景遮罩 | ○ | ○ | ○ | ● | +| 导出(图片、JSON、视频) | ○ | ○ | ○ | ● | +| 手动粒子 | ○ | ○ | ○ | ● | +| 响应式 | ○ | ○ | ○ | ● | +| 拖尾 | ○ | ○ | ○ | ● | +| 缩放 | ○ | ○ | ○ | ● | +| Poisson disc | ○ | ○ | ○ | ● | +| **路径** | | | | | +| 任意路径 | ○ | ○ | ○ | ●(14 种生成器) | +| **效果** | | | | | +| 气泡、滤镜、阴影等 | ○ | ○ | ○ | ●(5 种效果) | +| **缓动** | | | | | +| Quad | ○ | ● | ● | ● | +| Back、Bounce、Circ、Cubic、Elastic、Expo、Gaussian、Linear、Quart、Quint、Sigmoid、Sine、Smoothstep | ○ | ○ | ○ | ● | +| **颜色插件** | | | | | +| HEX、HSL、RGB | ● | ● | ● | ● | +| HSV、HWB、LAB、LCH、Named、OKLAB、OKLCH | ○ | ○ | ○ | ● | + +### 专用 API 捆绑包 + +| 功能 | confetti | fireworks | particles | ribbons | +| -------- | ----------------------------------------------------- | ------------------ | ----------------- | --------------- | +| 形状 | 圆形、心形、扑克花色、emoji、图片、多边形、方形、星形 | 线条 | (来自 basic) | 丝带 | +| 交互 | — | — | 连线 + 碰撞 | — | +| 特殊插件 | 发射器、动效 | 发射器、声音、混合 | — | 发射器、动效 | +| API 调用 | `confetti(opts)` | `fireworks(opts)` | `particles(opts)` | `ribbons(opts)` | + +## 选择指南 + +```mermaid +flowchart TD + A[需要快速上手?] -->|是| B[使用预设?] + A -->|否| C[需要多大的捆绑包?] + B -->|是| D["@tsparticles/configs + @tsparticles/slim"] + B -->|否| E["彩纸? → @tsparticles/confetti"] + B -->|否| F["烟花? → @tsparticles/fireworks"] + B -->|否| G["粒子背景? → @tsparticles/particles"] + B -->|否| H["丝带? → @tsparticles/ribbons"] + C -->|"最小(仅圆形)"| I["@tsparticles/basic"] + C -->|"中等(形状 + 交互)"| J["@tsparticles/slim"] + C -->|"最大(所有功能)"| K["tsparticles (loadFull)"] + C -->|"整个仓库"| L["@tsparticles/all"] ``` -需要 CDN 链接和更多包管理器变体? - -- 参见 [`/guide/installation`](/zh/guide/installation)。 - -## Setup 示例 - -### engine + loader bundles (`basic`, `slim`, `full`, `all`) - -```ts -import { tsParticles } from "@tsparticles/engine"; -import { loadSlim } from "@tsparticles/slim"; - -await loadSlim(tsParticles); - -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - number: { value: 80 }, - move: { enable: true, speed: 2 }, - }, - }, -}); +**经验法则:** + +1. 大多数项目从 `@tsparticles/slim` 开始。 +2. 如果捆绑包大小至关重要且你只需要圆形:`@tsparticles/basic`。 +3. 如果需要发射器、吸收器、文本、摆动/倾斜/滚动:`tsparticles` 配合 `loadFull`。 +4. 需要所有功能快速原型设计:`@tsparticles/all`。 +5. 针对特定效果(彩纸、烟花、粒子背景、丝带)且设置最简:专用 API 捆绑包。 + +## 快速安装 + +| 捆绑包 | npm 命令 | 加载器函数 | CDN URL | +| ------------------------ | ------------------------------------------------- | ------------------------ | -------------------------------------------------------------- | +| `@tsparticles/basic` | `pnpm add @tsparticles/engine @tsparticles/basic` | `loadBasic(tsParticles)` | `@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| `@tsparticles/slim` | `pnpm add @tsparticles/engine @tsparticles/slim` | `loadSlim(tsParticles)` | `@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| `tsparticles`(full) | `pnpm add @tsparticles/engine tsparticles` | `loadFull(tsParticles)` | `tsparticles@4/tsparticles.bundle.min.js` | +| `@tsparticles/all` | `pnpm add @tsparticles/engine @tsparticles/all` | `loadAll(tsParticles)` | `@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| `@tsparticles/confetti` | `pnpm add @tsparticles/confetti` | `confetti(opts)` | `@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| `@tsparticles/fireworks` | `pnpm add @tsparticles/fireworks` | `fireworks(opts)` | `@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| `@tsparticles/particles` | `pnpm add @tsparticles/particles` | `particles(opts)` | `@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| `@tsparticles/ribbons` | `pnpm add @tsparticles/ribbons` | `ribbons(opts)` | `@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | + +**注意:** 对于 basic/slim/full/all 捆绑包,你**必须**在 `tsParticles.load()` 之前调用 `load*` 函数。CDN 文件会全局暴露加载器函数,但**不会自动调用它**。confetti/fireworks/particles/ribbons 捆绑包拥有独立的 API——直接调用 `confetti()`、`fireworks()` 等即可。 + +`@tsparticles/slim` 的 CDN 示例: + +```html + + + ``` -其他 preset 只需要替换 loader 的 import/函数名: +`@tsparticles/confetti` 的 CDN 示例: -- `@tsparticles/basic` -> `loadBasic` -- `tsparticles` -> `loadFull` -- `@tsparticles/all` -> `loadAll` - -### 聚焦 API (`confetti`, `fireworks`, `particles`, `ribbons`) - -```ts -import { confetti } from "@tsparticles/confetti"; -import { fireworks } from "@tsparticles/fireworks"; -import { particles } from "@tsparticles/particles"; -import { ribbons } from "@tsparticles/ribbons"; - -await confetti({ count: 80, spread: 60 }); -await fireworks({ sounds: false }); -await particles({ count: 100, links: true }); -await ribbons({ count: 5, spread: 0 }); +```html + + ``` -当你希望快速接入、又不想手动串联大量 engine 插件时,这些 API 很合适。 - -## 实用选择规则 - -1. 大多数项目先从 `@tsparticles/slim` 开始。 -2. 若 bundle 体积是首要目标且功能需求简单,使用 `@tsparticles/basic`。 -3. 若你需要 full 基线并通过 `loadFull` 获得广泛能力,使用 `tsparticles`。 -4. 若是快速原型或立即需要大量功能,使用 `@tsparticles/all`。 -5. 若 UI 只需要单一聚焦效果并且希望最小 setup,使用 `@tsparticles/confetti`、`@tsparticles/fireworks`、`@tsparticles/particles` 或 `@tsparticles/ribbons`。 +另请参阅[安装指南](/zh/guide/installation)了解 CDN、npm、yarn 和文件详情。 ## 相关页面 -- Playground 聚焦 bundles:[`/playground/bundles`](/zh/playground/bundles) -- 快速入门路径:[`/guide/getting-started`](/zh/guide/getting-started) -- 安装矩阵:[`/guide/installation`](/zh/guide/installation) -- Wrappers 总览:[`/guide/wrappers`](/zh/guide/wrappers) +- [开始使用](/zh/guide/getting-started) +- [安装指南](/zh/guide/installation) +- [预设目录](/zh/demos/presets) +- [调色板目录](/zh/demos/palettes) +- [形状目录](/zh/demos/shapes) diff --git a/websites/website/docs/zh/guide/color-formats.md b/websites/website/docs/zh/guide/color-formats.md index 2dec95e1183..53699507aae 100644 --- a/websites/website/docs/zh/guide/color-formats.md +++ b/websites/website/docs/zh/guide/color-formats.md @@ -1,6 +1,6 @@ # 颜色格式 -tsParticles 接受跨选项(例如 `background`、`particles.color` 和插件设置)的多种颜色格式。 +tsParticles 接受跨选项(例如 `background`、`particles.paint` 和插件设置)的多种颜色格式。 ## 常用格式 diff --git a/websites/website/docs/zh/guide/getting-started.md b/websites/website/docs/zh/guide/getting-started.md index aad107d774b..179c25b401e 100644 --- a/websites/website/docs/zh/guide/getting-started.md +++ b/websites/website/docs/zh/guide/getting-started.md @@ -1,106 +1,197 @@ # 开始使用 -此路径是 2026 年 `tsParticles` 最快可靠的设置。 +tsParticles 是一个用于创建粒子动画、彩纸、烟花等的 JavaScript/TypeScript 库。它适用于所有现代浏览器,既可作为 npm 包使用,也可通过 CDN 配合 ` + + + + +
+ + + +``` + +> **注意**:即使使用 CDN 捆绑包,你**必须**在 `tsParticles.load()` 之前调用 `loadSlim(tsParticles)`(或 `loadBasic` / `loadFull` / `loadAll`)。CDN 捆绑包会全局暴露加载器函数,但**不会自动调用它**。 + +`@tsparticles/basic` → `loadBasic`、`tsparticles` → `loadFull`、`@tsparticles/all` → `loadAll`,同理。 + +### 路径 C — 具有专用 API 的专业捆绑包(彩纸、烟花、粒子) + +某些捆绑包拥有自己的简化 API,无需使用 `tsParticles.load()`: + +```html + + + + + + + + + +``` + +`fireworks()`、`particles()`、`ribbons()` 同理。 -- `@tsparticles/slim`:大多数应用程序应该从这里开始。 -- `@tsparticles/basic`:较小的功能集,适用于非常轻型的设置。 -- `@tsparticles/all`:包含所有内容,最适合快速原型设计。 +## 选择哪个捆绑包? -如果您需要一个集中的 API 而不是直接 `tsParticles` 设置: +| 捆绑包 | npm | 何时使用 | +| ------------------------ | ------------------------ | ------------------------------------------------------------------------------ | +| `@tsparticles/basic` | `loadBasic(tsParticles)` | 最简:圆形、移动、透明度、大小。无交互。 | +| `@tsparticles/slim` | `loadSlim(tsParticles)` | **推荐用于大多数项目。** 添加交互(点击/悬停)、粒子连线、图片、星形、多边形。 | +| `tsparticles` | `loadFull(tsParticles)` | 完整的官方功能集:发射器、吸收器、文本形状、滚动、摆动、拖尾。 | +| `@tsparticles/all` | `loadAll(tsParticles)` | **仓库中的所有内容**:每种形状、交互、效果、缓动、路径、导出。仅限原型设计。 | +| `@tsparticles/confetti` | `confetti(options)` | 一次函数调用即可实现彩纸效果。专用 API。 | +| `@tsparticles/fireworks` | `fireworks(options)` | 一次函数调用即可实现烟花效果。专用 API。 | +| `@tsparticles/particles` | `particles(options)` | 简化的粒子背景。专用 API。 | +| `@tsparticles/ribbons` | `ribbons(options)` | 丝带效果。专用 API。 | -- `@tsparticles/particles`:简化的粒子背景API -- `@tsparticles/confetti`:一次调用即可触发的彩纸 API -- `@tsparticles/fireworks`:一次调用即可触发的烟花 API +更多详情:[`/zh/guide/bundles`](/zh/guide/bundles)。 -## 5) 当您需要速度时使用预设/配置 +## 使用预设 -如果您更喜欢预置效果: +`@tsparticles/configs` 包包含数十种现成的配置(吸收器、气泡、雪、星星、重力、碰撞等)。 ```bash -pnpm add @tsparticles/configs +pnpm add @tsparticles/engine @tsparticles/slim @tsparticles/configs +``` + +```ts +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import "@tsparticles/configs"; + +await loadSlim(tsParticles); + +await tsParticles.load({ + id: "tsparticles", + options: { preset: "snow" }, +}); ``` -然后通过按键加载一个配置,例如 [`demo/vite` app](https://github.com/tsparticles/tsparticles/blob/main/demo/vite/src/main.ts)。 +通过 CDN: -如果您更喜欢基于预设名称的设置,请使用 [`/demos/presets`](/zh/demos/presets) 中的官方预设目录。 +```html + + + + +``` -## 快速文档地图 +## 快速参考 -- 根选项:[`/options/`](/zh/options/) -- wrappers 参考:[`/guide/wrappers`](/zh/guide/wrappers) -- 预设目录:[`/demos/presets`](/zh/demos/presets) -- 调色板目录:[`/demos/palettes`](/zh/demos/palettes) -- 形状目录:[`/demos/shapes`](/zh/demos/shapes) -- 从 particles.js 迁移:[`/migrations/particles-js`](/zh/migrations/particles-js) -- 颜色格式:[`/guide/color-formats`](/zh/guide/color-formats) -- 容器生命周期:[`/guide/container-lifecycle`](/zh/guide/container-lifecycle) -- 插件和自定义:[`/guide/plugins-customization`](/zh/guide/plugins-customization) +- 选项文档:[`/zh/options/`](/zh/options/) +- 捆绑包指南:[`/zh/guide/bundles`](/zh/guide/bundles) +- 预设目录:[`/zh/demos/presets`](/zh/demos/presets) +- 调色板目录:[`/zh/demos/palettes`](/zh/demos/palettes) +- 形状目录:[`/zh/demos/shapes`](/zh/demos/shapes) +- 框架封装器:[`/zh/guide/wrappers`](/zh/guide/wrappers) +- 颜色格式:[`/zh/guide/color-formats`](/zh/guide/color-formats) +- 容器生命周期:[`/zh/guide/container-lifecycle`](/zh/guide/container-lifecycle) +- 插件与自定义:[`/zh/guide/plugins-customization`](/zh/guide/plugins-customization) ## 故障排除 -- 空白屏幕:在调用 `tsParticles.load` 之前先确认 `#tsparticles` 存在。 -- 缺少功能:您可能需要另一个插件/包(形状、交互、更新程序)。 -- 选项上的类型错误:使您的包保持与相同的主要/次要版本一致。 +| 问题 | 可能原因 | 解决方案 | +| ---------------------------------------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------- | +| 空白屏幕,无粒子 | 调用 `tsParticles.load()` 时 `#tsparticles` 在 DOM 中不存在 | 确保 DIV 在脚本之前存在,或使用 `DOMContentLoaded` | +| 空白屏幕,无粒子 | 只安装了 `@tsparticles/engine` | 同时安装一个捆绑包(`@tsparticles/slim`)或插件——引擎本身没有可绘制的形状 | +| "loadBasic/loadSlim/loadFull is not a function" 错误 | 未安装捆绑包或导入错误 | `pnpm add @tsparticles/slim` 并导入 `{ loadSlim }` | +| 粒子不移动 | `move.enable` 未设置为 `true` | 添加 `move: { enable: true, speed: 2 }` | +| 缺少功能(如连线、碰撞) | 选择的捆绑包不包含该功能 | 切换到更丰富的捆绑包(`@tsparticles/slim` 或 `tsparticles`)或安装特定插件 | +| TypeScript 类型错误 | 包版本不同步 | 保持引擎和捆绑包的主/次版本一致 | diff --git a/websites/website/docs/zh/guide/installation.md b/websites/website/docs/zh/guide/installation.md index e735df25ecb..f19797d66fc 100644 --- a/websites/website/docs/zh/guide/installation.md +++ b/websites/website/docs/zh/guide/installation.md @@ -1,109 +1,146 @@ # 安装 -本页对应 `tsParticles` 主 README 中的安装矩阵。 - -官方参考: - ## 选择你的路径 -- **快速默认**: `@tsparticles/engine` + `@tsparticles/slim` -- **更小的自定义 runtime**: `@tsparticles/engine` + 仅所需 plugins -- **聚焦 API**: `@tsparticles/particles`、`@tsparticles/confetti`、`@tsparticles/fireworks` 或 `@tsparticles/ribbons` -- **包含全部功能**: `@tsparticles/all` - -## 托管 / CDN - -可使用以下提供商(或自行托管构建产物)。 +| 场景 | 命令 | +| ---------------- | ------------------------------------------------- | +| 快速开始(推荐) | `pnpm add @tsparticles/engine @tsparticles/slim` | +| 最小设置 | `pnpm add @tsparticles/engine @tsparticles/basic` | +| 完整功能集 | `pnpm add @tsparticles/engine tsparticles` | +| 仓库中所有内容 | `pnpm add @tsparticles/engine @tsparticles/all` | +| 仅彩纸 | `pnpm add @tsparticles/confetti` | +| 仅烟花 | `pnpm add @tsparticles/fireworks` | +| 粒子背景 | `pnpm add @tsparticles/particles` | +| 丝带效果 | `pnpm add @tsparticles/ribbons` | -### jsDelivr +> **重要**:`@tsparticles/engine` 单独使用不绘制任何内容。你必须始终添加一个捆绑包(以加载形状和动画)或单个插件。请参阅[捆绑包指南](/zh/guide/bundles)。 -- -- -- -- -- -- -- -- +## npm -### cdnjs +```bash +# 引擎 + slim(推荐用于大多数项目) +npm install @tsparticles/engine @tsparticles/slim -- +# 引擎 + basic(最小化) +npm install @tsparticles/engine @tsparticles/basic -### unpkg +# 引擎 + full(tsparticles) +npm install @tsparticles/engine tsparticles -- -- -- -- -- -- -- -- +# 引擎 + all +npm install @tsparticles/engine @tsparticles/all -## 使用 package manager 安装 +# 专用 API 捆绑包(无需显式安装引擎) +npm install @tsparticles/confetti +npm install @tsparticles/fireworks +npm install @tsparticles/particles +npm install @tsparticles/ribbons +``` -### npm +## yarn ```bash -npm install @tsparticles/engine +yarn add @tsparticles/engine @tsparticles/slim +# ... 其他捆绑包同理 ``` -### yarn +## pnpm ```bash -yarn add @tsparticles/engine +pnpm add @tsparticles/engine @tsparticles/slim +# ... 其他捆绑包同理 ``` -### pnpm +## CDN(script 标签) -```bash -pnpm add @tsparticles/engine -``` +所有包均可通过 jsDelivr、unpkg 和 cdnjs 获取。 -## import 与 require +### jsDelivr -```ts -const tsParticles = require("@tsparticles/engine"); +| 捆绑包 | URL | +| -------------------- | ------------------------------------------------------------------------------------------- | +| 引擎 | `https://cdn.jsdelivr.net/npm/@tsparticles/engine@4/tsparticles.engine.min.js` | +| Basic | `https://cdn.jsdelivr.net/npm/@tsparticles/basic@4/tsparticles.basic.bundle.min.js` | +| Slim | `https://cdn.jsdelivr.net/npm/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` | +| Full (`tsparticles`) | `https://cdn.jsdelivr.net/npm/tsparticles@4/tsparticles.bundle.min.js` | +| All | `https://cdn.jsdelivr.net/npm/@tsparticles/all@4/tsparticles.all.bundle.min.js` | +| Confetti | `https://cdn.jsdelivr.net/npm/@tsparticles/confetti@4/tsparticles.confetti.bundle.min.js` | +| Fireworks | `https://cdn.jsdelivr.net/npm/@tsparticles/fireworks@4/tsparticles.fireworks.bundle.min.js` | +| Particles | `https://cdn.jsdelivr.net/npm/@tsparticles/particles@4/tsparticles.particles.bundle.min.js` | +| Ribbons | `https://cdn.jsdelivr.net/npm/@tsparticles/ribbons@4/tsparticles.ribbons.bundle.min.js` | +| particles.js 兼容 | `https://cdn.jsdelivr.net/npm/@tsparticles/pjs@4/tsparticles.pjs.min.js` | -// or +### unpkg -import { tsParticles } from "@tsparticles/engine"; -``` +相同结构:`https://unpkg.com/{包名}@{版本}/{文件名}` -## 最小 runtime 配置(`@tsparticles/slim`) +示例: +`https://unpkg.com/@tsparticles/slim@4/tsparticles.slim.bundle.min.js` + +### cdnjs + +`https://cdnjs.com/libraries/tsparticles` + +## 导入示例 + +### 使用打包工具(ES module 导入) ```ts +// 引擎 + 捆绑包加载器 import { tsParticles } from "@tsparticles/engine"; import { loadSlim } from "@tsparticles/slim"; await loadSlim(tsParticles); +await tsParticles.load({ id: "tsparticles", options: { ... } }); +``` -await tsParticles.load({ - id: "tsparticles", - options: { - particles: { - move: { - enable: true, - }, - number: { - value: 60, - }, - }, - }, -}); +### 使用 CommonJS(require) + +```ts +const { tsParticles } = require("@tsparticles/engine"); +const { loadSlim } = require("@tsparticles/slim"); + +(async () => { + await loadSlim(tsParticles); + await tsParticles.load({ id: "tsparticles", options: { ... } }); +})(); ``` -## 相关页面 +### 使用 CDN(script 标签) + +```html + + + + + + +``` -- [`/guide/getting-started`](/zh/guide/getting-started) -- [`/guide/wrappers`](/zh/guide/wrappers) -- [`/demos/presets`](/zh/demos/presets) -- [`/migrations/particles-js`](/zh/migrations/particles-js) +使用专用 API 捆绑包: -## 旧版兼容 +```html + + +``` -如果你在迁移旧的 particles.js 集成,请使用兼容包: +## 相关页面 -- npm: -- jsDelivr: +- [开始使用](/zh/guide/getting-started) +- [捆绑包指南](/zh/guide/bundles) +- [框架封装器](/zh/guide/wrappers) diff --git a/websites/website/docs/zh/guides/angular.md b/websites/website/docs/zh/guides/angular.md new file mode 100644 index 00000000000..3b8fe0434b7 --- /dev/null +++ b/websites/website/docs/zh/guides/angular.md @@ -0,0 +1,631 @@ +--- +title: Angular 集成 +description: 将 tsParticles 集成到 Angular 应用中的分步指南,使用 @tsparticles/angular。 +--- + +# Angular 集成 + +`@tsparticles/angular` 包提供了用于 tsParticles 的 Angular 组件、模块和服务。本指南涵盖了传统的 `NgModule` 方式以及 Angular 17+ 的独立组件。 + +--- + +## 安装 + +```bash +npm install @tsparticles/angular @tsparticles/engine +``` + +如需完整功能集,请安装完整包: + +```bash +npm install tsparticles +``` + +可选的预设包: + +```bash +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +``` + +--- + +## 基本使用(NgModule) + +### 1. 导入模块 + +```typescript +import { NgModule } from "@angular/core"; +import { BrowserModule } from "@angular/platform-browser"; +import { NgParticlesModule } from "@tsparticles/angular"; +import { AppComponent } from "./app.component"; + +@NgModule({ + declarations: [AppComponent], + imports: [BrowserModule, NgParticlesModule], + bootstrap: [AppComponent], +}) +export class AppModule {} +``` + +### 2. 初始化引擎 + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d47a1", + }, + fpsLimit: 120, + particles: { + number: { + value: 80, + }, + color: { + value: "#ffffff", + }, + shape: { + type: "circle", + }, + opacity: { + value: 0.5, + }, + size: { + value: { min: 1, max: 5 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("粒子容器已加载", container); + } +} +``` + +### 3. 模板 + +```html + +``` + +--- + +## 引擎初始化详情 + +`NgParticlesService.init()` 方法必须且只调用一次,通常在 `AppComponent.ngOnInit()` 中调用。它接收一个回调函数,在其中加载应用所需的插件/预设。 + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesService } from "@tsparticles/angular"; +import type { Engine } from "@tsparticles/engine"; + +@Component({ ... }) +export class AppComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + // 只加载所需功能以减小打包体积 + await loadBasic(engine); // 基础形状 + 移动 + await loadEmittersPlugin(engine); // 发射器形状 + }); + } +} +``` + +从 `tsparticles` 可用的加载函数: + +| 函数 | 描述 | +| ------------------- | -------------------------------- | +| `loadFull(engine)` | 所有功能(最大包) | +| `loadBasic(engine)` | 核心形状(圆形、方形、多边形等) | +| `loadSlim(engine)` | 大部分功能,移除不常用插件 | +| `loadAll(engine)` | `loadFull` 的已弃用别名 | + +--- + +## 五彩纸屑效果 + +```bash +npm install @tsparticles/preset-confetti +``` + +```typescript +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// 在 NgParticlesService.init 回调中: +await loadConfettiPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "confetti", + background: { + color: "transparent", + }, +}; +``` + +或者使用便捷的 `` 组件: + +```typescript +// app.module.ts +import { NgParticlesModule } from "@tsparticles/angular"; + +@NgModule({ + imports: [NgParticlesModule], +}) +export class AppModule {} +``` + +```html + +``` + +--- + +## 烟花效果 + +```bash +npm install @tsparticles/preset-fireworks +``` + +```typescript +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; + +// 在 NgParticlesService.init 回调中: +await loadFireworksPreset(engine); +``` + +```typescript +particlesOptions: ISourceOptions = { + preset: "fireworks", + background: { + color: "#000000", + }, +}; +``` + +或者使用 `` 组件: + +```html + +``` + +> 避免自动启动烟花效果;将其绑定到用户操作(点击、滚动)上,以防止不必要的资源消耗。 + +--- + +## 自定义粒子配置 + +带交互功能的完整自定义粒子设置: + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-particles", + templateUrl: "./particles.component.html", +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { + color: "#0d0d0d", + }, + fpsLimit: 60, + particles: { + number: { + value: 100, + density: { + enable: true, + }, + }, + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + shape: { + type: ["circle", "square", "triangle"], + }, + opacity: { + value: 0.8, + random: true, + anim: { + enable: true, + speed: 1, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + random: true, + anim: { + enable: true, + speed: 4, + size_min: 1, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.3, + width: 1, + triangles: { + enable: true, + color: "#ffffff", + opacity: 0.05, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { + enable: true, + rotateX: 600, + rotateY: 600, + }, + }, + life: { + duration: { + value: 5, + random: true, + }, + count: 0, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: { + enable: true, + }, + }, + modes: { + grab: { + distance: 200, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + detectRetina: true, + }; + + particlesLoaded(container: Container): void { + console.log("容器已加载", container); + } +} +``` + +```html + +``` + +--- + +## 事件 + +`ngx-particles` 组件触发 `particlesLoaded` 事件: + +```typescript +import type { Container } from "@tsparticles/engine"; + +// 组件方法 +onParticlesLoaded(container: Container): void { + // 访问容器 API + container.pause(); + container.play(); + container.destroy(); + container.exportImage().then((blob) => { /* ... */ }); +} +``` + +```html + +``` + +容器引用让你拥有完整的程序化控制权:暂停、恢复、销毁、导出等功能。 + +--- + +## 模板语法与条件渲染 + +使用 Angular 结构型指令来切换组件: + +```html + + + +``` + +```typescript +export class AppComponent { + showParticles = true; + // ... +} +``` + +当 `*ngIf` 求值为 `false` 时,组件(包括画布和所有粒子实例)将被销毁。重新创建时将从头开始重新初始化。 + +--- + +## 独立组件(Angular 17+) + +在 Angular 17+ 中,你可以直接将 `NgParticlesModule` 导入到独立组件中: + +```typescript +import { Component, OnInit } from "@angular/core"; +import { NgParticlesModule, NgParticlesService } from "@tsparticles/angular"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +@Component({ + selector: "app-particles", + standalone: true, + imports: [NgParticlesModule], + template: ` + + `, +}) +export class ParticlesComponent implements OnInit { + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadFull(engine); + }); + } + + particlesOptions: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 50 }, + color: { value: "#fff" }, + shape: { type: "circle" }, + move: { enable: true, speed: 2 }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("已加载", container); + } +} +``` + +无需 `NgModule` 包装——只需在组件的 `imports` 数组中导入 `NgParticlesModule`。 + +--- + +## 完整组件示例 + +### app.component.ts + +```typescript +import { Component, OnInit } from "@angular/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; +import { NgParticlesService } from "@tsparticles/angular"; + +@Component({ + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"], +}) +export class AppComponent implements OnInit { + title = "tsParticles Angular 演示"; + + constructor(private readonly ngParticlesService: NgParticlesService) {} + + ngOnInit(): void { + void this.ngParticlesService.init(async (engine: Engine) => { + await loadSlim(engine); + }); + } + + particlesOptions: ISourceOptions = { + autoPlay: true, + background: { + color: "#1e1e2e", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMask: { + cover: { + color: "#1e1e2e", + }, + enable: false, + }, + fullScreen: { + enable: true, + zIndex: -1, + }, + detectRetina: true, + fpsLimit: 60, + particles: { + color: { + value: "#cdd6f4", + }, + links: { + color: "#cdd6f4", + distance: 150, + enable: true, + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1, + }, + number: { + value: 60, + }, + opacity: { + value: 0.6, + }, + size: { + value: { min: 1, max: 3 }, + }, + }, + }; + + particlesLoaded(container: Container): void { + console.log("粒子已加载", container); + } +} +``` + +### app.component.html + +```html +
+ + +
+

{{ title }}

+

粒子正在后台运行。

+
+
+``` + +### app.component.css + +```css +:host { + display: block; + width: 100%; + height: 100%; +} +``` + +--- + +## API 参考 + +| 组件 | 选择器 | 描述 | +| -------- | --------------- | -------------------- | +| 粒子 | `ngx-particles` | 完整的粒子系统组件 | +| 五彩纸屑 | `ngx-confetti` | 预配置的五彩纸屑效果 | +| 烟花 | `ngx-fireworks` | 预配置的烟花效果 | + +### `ngx-particles` 输入属性 + +| 输入属性 | 类型 | 默认值 | 描述 | +| --------- | ---------------- | --------------- | ------------------ | +| `id` | `string` | `"tsparticles"` | 画布元素 ID | +| `options` | `ISourceOptions` | `{}` | 粒子配置 | +| `url` | `string` | — | 远程 JSON 配置 URL | + +### `ngx-particles` 输出事件 + +| 输出事件 | 负载类型 | 描述 | +| ----------------- | ----------- | ---------------------- | +| `particlesLoaded` | `Container` | 当容器初始化完成时触发 | + +--- + +## 故障排除 + +- **空白/不可见画布** — 确保父元素有明确的高度(例如 `height: 100vh`)。画布会采用容器尺寸。 +- **`NgParticlesService.init()` 被多次调用** — 只调用一次,通常在 `AppComponent.ngOnInit()` 中。后续调用安全但多余。 +- **找不到模块** — 确认 `@tsparticles/angular` 已在 `package.json` 的依赖项中列出,并且已导入 `NgParticlesModule`。 +- **`NullInjectorError: No provider for NgParticlesService`** — 你必须在提供该组件的模块中导入 `NgParticlesModule`(或重新导出它)。 diff --git a/websites/website/docs/zh/guides/astro.md b/websites/website/docs/zh/guides/astro.md new file mode 100644 index 00000000000..f412ba5bb5c --- /dev/null +++ b/websites/website/docs/zh/guides/astro.md @@ -0,0 +1,384 @@ +# Astro 集成 + +在你的 Astro 站点中使用官方 `@tsparticles/astro` 集成包来使用 tsParticles。 + +## 安装 + +通过包管理器安装 Astro 集成和 tsParticles 核心: + +```bash +npm install @tsparticles/astro tsparticles +``` + +```bash +pnpm add @tsparticles/astro tsparticles +``` + +```bash +yarn add @tsparticles/astro tsparticles +``` + +## 引擎初始化 + +tsParticles 采用模块化架构。在渲染粒子之前,你需要用所需功能初始化引擎。创建一个客户端脚本(例如 `src/scripts/particles-init.ts`)或在 Astro 组件中使用内联 ` +``` + +> `id` 属性会传递给底层画布容器 `
`。可将其用于样式设置或通过 `document.getElementById()` 进行命令式访问。 + +## TypeScript 支持 + +该集成包附带完整的 TypeScript 声明。使用 `@tsparticles/engine` 中的 `ISourceOptions` 对配置进行类型化: + +```typescript +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { + value: 50, + density: { enable: true }, + }, + opacity: { value: 0.5 }, + shape: { type: "circle" }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + repulse: { distance: 200 }, + }, + }, +}; +``` + +## 自定义配置 + +以下是一个更精细的配置,可直接放入任何 Astro 页面: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + autoPlay: true, + background: { + color: "#0d47a1", + image: "", + position: "50% 50%", + repeat: "no-repeat", + size: "cover", + }, + backgroundMode: { + enable: true, + zIndex: -1, + }, + fpsLimit: 120, + particles: { + color: { + value: "#ffffff", + animation: { + enable: true, + speed: 20, + sync: false, + }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + triangles: { + enable: true, + opacity: 0.1, + }, + }, + move: { + enable: true, + speed: 3, + direction: "none", + random: true, + straight: false, + outModes: "out", + attract: { enable: false }, + }, + number: { + value: 80, + density: { + enable: true, + }, + }, + opacity: { + value: 0.5, + animation: { + enable: true, + speed: 1, + sync: false, + }, + }, + shape: { + type: "circle", + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 3, + sync: false, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + resize: true, + }, + modes: { + grab: { + distance: 200, + links: { opacity: 0.5 }, + }, + push: { quantity: 4 }, + }, + }, + detectRetina: true, +}; +--- + + + + +``` + +## 使用预设 + +与其手动构建配置,不如在引擎初始化时加载预设并在选项中引用: + +```astro +--- +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + preset: "stars", + background: { color: "#000000" }, +}; +--- + + + + +``` + +## 与其他框架集成 + +由于 Astro 支持 React、Vue、Svelte 和 Solid 等 UI 框架,你可以在 `.astro` 文件中使用特定框架的 tsParticles 组件: + +### React 在 Astro 中 + +```astro +--- +import Particles from "@tsparticles/react"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +### Vue 在 Astro 中 + +```astro +--- +import Particles from "@tsparticles/vue3"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#000" }, + particles: { + number: { value: 60 }, + links: { enable: true }, + move: { enable: true }, + }, +}; +--- + + +``` + +> `client:load` 指令告诉 Astro 在页面加载时立即水合组件。使用 `client:visible` 可延迟加载。 + +## 完整页面示例 + +一个完整的 Astro 页面,粒子作为动画背景: + +```astro +--- +import Layout from "../layouts/Layout.astro"; +import Particles from "@tsparticles/astro"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + background: { color: "#0d47a1" }, + fpsLimit: 60, + particles: { + number: { value: 100 }, + color: { value: "#ffffff" }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 2, + outModes: "out", + }, + size: { + value: { min: 1, max: 4 }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, +}; +--- + + +
+

欢迎

+

此页面拥有由 tsParticles 驱动的粒子背景。

+
+ +
+ + + + +``` + +## 组件属性 + +| 属性 | 类型 | 默认值 | 描述 | +| -------------------- | ---------------- | ------------------------- | --------------------------------------- | +| `id` | `string` | `"tsparticles"` | 容器的 DOM 元素 ID | +| `options` | `ISourceOptions` | `{}` | 完整的 tsParticles 配置对象 | +| `url` | `string` | — | 从远程 JSON URL 加载配置 | +| `particlesClassName` | `string` | `"tsparticles-canvas-el"` | 画布元素的 CSS 类名 | +| `container` | `object` | — | 预先存在的 `Container` 实例(高级用法) | diff --git a/websites/website/docs/zh/guides/ember.md b/websites/website/docs/zh/guides/ember.md new file mode 100644 index 00000000000..d22564bd147 --- /dev/null +++ b/websites/website/docs/zh/guides/ember.md @@ -0,0 +1,346 @@ +--- +title: Ember 指南 +description: 将 tsParticles 与 Ember.js 应用集成的完整指南。 +--- + +# Ember 指南 + +## 目录 + +1. [安装](#installation) +2. [引擎初始化](#engine-initialization) +3. [基本使用](#basic-usage) +4. [自定义配置](#custom-configuration) +5. [事件处理](#event-handling) +6. [条件渲染](#conditional-rendering) +7. [TypeScript 示例](#typescript-example) + +--- + +## 安装 + +通过 ember-cli 安装 Ember 插件和 tsParticles 引擎: + +```bash +ember install @tsparticles/ember +``` + +这将安装插件及其对等依赖 `tsparticles`。你也可以选择添加预设包: + +```bash +npm install @tsparticles/slim +``` + +--- + +## 引擎初始化 + +该插件导出一个 `initParticlesEngine` 工具函数,在应用级别调用一次。它接收一个异步回调,在其中加载应用所需的功能、预设或形状。 + +```typescript +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadFull } from "tsparticles"; + +// 在应用启动时调用 +if (typeof window !== "undefined") { + void initParticlesEngine(async (engine) => { + await loadFull(engine); + }); +} +``` + +调用的典型位置是应用路由的 `beforeModel` 钩子、应用控制器的构造函数或实例初始化器。引擎单例初始化一次,并在应用中所有 `` 组件之间共享。 + +--- + +## 基本使用 + +初始化引擎后,在任何模板中使用 `` 组件。通过 `@options` 参数传入粒子配置。 + +```hbs +{{! app/templates/application.hbs }} + + +``` + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, + }; +} +``` + +--- + +## 自定义配置 + +构建一个更丰富的配置,包含交互功能、多种形状和响应式密度。 + +```typescript +import Controller from "@ember/controller"; +import type { ISourceOptions } from "@tsparticles/engine"; + +export default class IndexController extends Controller { + options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, + }; +} +``` + +```hbs + +``` + +--- + +## 事件处理 + +`` 组件在容器完成初始化并渲染第一帧时触发 `@particlesLoaded` 动作。使用此事件访问 `Container` 实例以进行程序化控制。 + +```typescript +import Controller from "@ember/controller"; +import { action } from "@ember/object"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default class ApplicationController extends Controller { + options: ISourceOptions = { + /* ... */ + }; + + @action + loadedCallback(container: Container) { + console.log("粒子已加载", container.id); + + // 程序化控制示例: + setTimeout(() => { + container.pause(); + console.log("粒子在 5 秒后暂停"); + }, 5000); + } +} +``` + +```hbs + +``` + +如果你不想单独定义一个动作,也可以使用模板辅助函数内联使用回调模式。 + +--- + +## 条件渲染 + +使用 Ember 的 `{{if}}` 辅助函数配合 `@tracked` 属性来控制 `` 组件的渲染时机。当引擎初始化是异步且你希望在引擎就绪前避免渲染组件时,这非常有用。 + +```typescript +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked engineReady = false; + + options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { enable: true, speed: 1, outModes: { default: "bounce" } }, + }, + background: { color: "#1a1a2e" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } +} +``` + +```hbs +{{#if this.engineReady}} + +{{else}} +

正在加载粒子...

+{{/if}} +``` + +`@tracked` 装饰器确保 Promise 解析后模板会自动重新渲染。 + +--- + +## TypeScript 示例 + +以下是一个完整的、带类型标注的 Ember 应用控制器,演示了使用 slim 预设、交互功能和生命周期管理的完整集成模式。 + +```typescript +// app/controllers/application.ts +import Controller from "@ember/controller"; +import { tracked } from "@glimmer/tracking"; +import { action } from "@ember/object"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { initParticlesEngine } from "@tsparticles/ember/utils/init-particles-engine"; +import { loadSlim } from "@tsparticles/slim"; + +export default class ApplicationController extends Controller { + @tracked private engineReady = false; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + constructor(...args: any[]) { + super(...args); + if (typeof window !== "undefined") { + void initParticlesEngine(async (engine: Engine) => { + await loadSlim(engine); + }).then(() => { + this.engineReady = true; + }); + } + } + + @action + private handleParticlesLoaded(container: Container): void { + this.container = container; + console.log("粒子已在容器中加载:", container.id); + } +} +``` + +```hbs +{{! app/templates/application.hbs }} + +{{#if this.engineReady}} +
+

tsParticles + Ember

+ +
+{{else}} +
+

正在初始化粒子引擎...

+
+{{/if}} +``` + +--- + +你现在已拥有将 tsParticles 集成到 Ember.js 应用所需的全部内容。每个示例都是独立的,可直接复制到你的项目中。 diff --git a/websites/website/docs/zh/guides/index.md b/websites/website/docs/zh/guides/index.md new file mode 100644 index 00000000000..c0d09c5b2e1 --- /dev/null +++ b/websites/website/docs/zh/guides/index.md @@ -0,0 +1,58 @@ +--- +title: 分步指南 +description: 探索将 tsParticles 集成到你的项目中的框架特定指南。 +--- + +# 分步指南 + +欢迎来到 tsParticles 指南部分。无论你是在构建静态的 Vanilla JS 站点、React 或 Vue 的单页应用,还是使用 Next.js 或 Nuxt 的全栈应用,这些分步教程将引导你完成安装、基本使用、高级配置和交互效果。 + +每个指南都是独立的,包含可直接复制粘贴的代码示例,让你快速上手。 + +## 可用指南 + +| 框架 / 封装 | 包 | 描述 | +| --------------------------------- | ------------------------------------ | ------------------------------------------- | +| [Vanilla JS](./vanilla) | `tsparticles`(CDN 或 npm) | 使用 `tsParticles.load()` 进行直接 DOM 集成 | +| [React](./react) | `@tsparticles/react` | 官方 React 封装,提供 Hooks 和组件 API | +| [Vue 3](./vue3) | `@tsparticles/vue3` | 官方 Vue 3 插件,提供组合式 API | +| [Angular](./angular) | `@tsparticles/angular` | 官方 Angular 组件和模块 | +| [Svelte](./svelte) | `@tsparticles/svelte` | 官方 Svelte 组件 | +| [Next.js](./nextjs) | `@tsparticles/react`(配合 Next.js) | 服务端渲染和动态导入 | +| [Nuxt](./nuxt) | `@tsparticles/vue3`(配合 Nuxt) | 以 Nuxt 插件形式实现的 SSR 安全集成 | +| [Solid](./solid) | `@tsparticles/solid` | 官方 SolidJS 封装 | +| [Preact](./preact) | `@tsparticles/preact` | Preact 兼容组件 | +| [Lit](./lit) | `@tsparticles/lit` | Lit Web 组件封装 | +| [Qwik](./qwik) | `@tsparticles/qwik` | Qwik 优化集成 | +| [jQuery](./jquery) | `@tsparticles/jquery` | 用于遗留项目的 jQuery 插件 | +| [Astro](./astro) | `@tsparticles/react`(或任意封装) | 支持 Island 架构和客户端指令 | +| [Web Components](./webcomponents) | `@tsparticles/webcomponents` | 自定义元素 API 集成 | +| [Stencil](./stencil) | `@tsparticles/stencil` | Stencil 组件封装 | +| [Ember](./ember) | `@tsparticles/ember` | Ember 插件集成 | +| [Riot](./riot) | `@tsparticles/riot` | Riot.js 封装 | +| [Inferno](./inferno) | `@tsparticles/inferno` | Inferno 兼容组件 | +| [WordPress](./wordpress) | 插件 + `tsparticles` | 块编辑器 / 短代码集成 | + +## 选择你的指南 + +- [Vanilla JS(纯 JavaScript)](./vanilla) +- [React](./react) +- [Vue 3](./vue3) +- [Angular](./angular) +- [Svelte](./svelte) +- [Next.js](./nextjs) +- [Nuxt](./nuxt) +- [Solid](./solid) +- [Preact](./preact) +- [Lit](./lit) +- [Qwik](./qwik) +- [jQuery](./jquery) +- [Astro](./astro) +- [Web Components](./webcomponents) +- [Stencil](./stencil) +- [Ember](./ember) +- [Riot](./riot) +- [Inferno](./inferno) +- [WordPress](./wordpress) + +祝构建愉快! diff --git a/websites/website/docs/zh/guides/inferno.md b/websites/website/docs/zh/guides/inferno.md new file mode 100644 index 00000000000..91f982b4dd6 --- /dev/null +++ b/websites/website/docs/zh/guides/inferno.md @@ -0,0 +1,373 @@ +--- +title: Inferno 指南 +description: 将 tsParticles 与 Inferno 应用集成的完整指南。 +--- + +# Inferno 指南 + +## 目录 + +1. [安装](#installation) +2. [基本使用](#basic-usage) +3. [引擎初始化](#engine-initialization) +4. [自定义配置](#custom-configuration) +5. [预设使用](#preset-usage) +6. [组件模式](#component-pattern) +7. [TypeScript 示例](#typescript-example) + +--- + +## 安装 + +通过 npm 安装 Inferno 封装和 tsParticles 引擎: + +```bash +npm install @tsparticles/inferno tsparticles +``` + +可选安装 slim 预设以获得更小的打包体积: + +```bash +npm install @tsparticles/slim +``` + +--- + +## 基本使用 + +`@tsparticles/inferno` 包导出两个项目:`ParticlesProvider` 和 `Particles`。用 `ParticlesProvider` 包裹粒子组件,它接受一个用于引擎设置的 `init` 回调,然后使用 `` 渲染粒子画布。 + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import { loadSlim } from "@tsparticles/slim"; + +const options = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +function App() { + return ( + { + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +`ParticlesProvider` 必须是每个 `` 组件的祖先。它初始化引擎一次,并通过上下文将其提供给所有子组件。 + +--- + +## 引擎初始化 + +`ParticlesProvider` 接受一个 `init` 属性,该属性接收引擎实例。在这里加载应用所需的功能、形状、预设或更新器。 + +```tsx +// 轻量级 — 圆形粒子、基本移动、连线 + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); +}}> + +// 完整功能集 — 所有形状、交互、效果 + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); +}}> + +// 特定预设 — 五彩纸屑、烟花、雪花、星星 + { + const { loadConfettiPreset } = await import("@tsparticles/preset-confetti"); + await loadConfettiPreset(engine); +}}> +``` + +在回调中使用动态 `import()` 可以实现代码分割:预设或功能模块仅在粒子组件挂载时加载。 + +--- + +## 自定义配置 + +以下是一个包含交互功能、多种形状类型和深色渐变背景的完整配置。 + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { color: "#0f0f23" }, +}; + +function App() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +--- + +## 预设使用 + +`@tsparticles/configs` 包提供预构建的配置,你可以直接传递给 `options` 属性。在 `ParticlesProvider` 的 init 回调中使用相应的预设加载器。 + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import configs from "@tsparticles/configs"; + +function App() { + return ( + { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }} + > + + + ); +} + +render(, document.getElementById("app")); +``` + +你可以将 `configs.confetti` 替换为任何可用的预设:`configs.basic`、`configs.fireworks`、`configs.snow`、`configs.stars` 等。 + +--- + +## 组件模式 + +对于较大的应用,将粒子逻辑组织到专用组件中,并使用 `particlesLoaded` 回调来访问 `Container` 实例。 + +```tsx +import { render, Component } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +class ParticlesBackground extends Component { + private container?: Container; + + handleParticlesLoaded(container?: Container) { + this.container = container; + console.log("粒子已加载:", container?.id); + } + + render() { + return ( + { + const { loadSlim } = await import("@tsparticles/slim"); + await loadSlim(engine); + }} + > + + + ); + } +} + +function App() { + return ( +
+

tsParticles + Inferno

+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +## TypeScript 示例 + +以下是一个完整的、带类型标注的 Inferno 应用,包含响应式粒子配置和全屏背景。 + +```tsx +import { render } from "inferno"; +import { Particles, ParticlesProvider } from "@tsparticles/inferno"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const particlesOptions: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, +}; + +function handleInit(engine: Engine): Promise { + return import("@tsparticles/slim").then(({ loadSlim }) => loadSlim(engine)); +} + +function handleParticlesLoaded(container?: Container): void { + console.log("tsParticles 容器就绪:", container?.id); +} + +function App() { + return ( + +
+

tsParticles + Inferno

+

完整 TypeScript 集成

+
+ +
+ ); +} + +render(, document.getElementById("app")); +``` + +--- + +你现在已拥有将 tsParticles 集成到 Inferno 应用所需的全部内容。每个示例都是独立的,可直接复制到你的项目中。 diff --git a/websites/website/docs/zh/guides/jquery.md b/websites/website/docs/zh/guides/jquery.md new file mode 100644 index 00000000000..8daf6b93ac6 --- /dev/null +++ b/websites/website/docs/zh/guides/jquery.md @@ -0,0 +1,274 @@ +# jQuery 集成 + +使用官方 jQuery 插件封装将 tsParticles 集成到你的 jQuery 项目中。 + +## 安装 + +### 通过 CDN + +通过 script 标签引入 jQuery、tsParticles 和 jQuery 插件: + +```html + + + +``` + +--- + +### 通过 npm + 构建 + +安装所需包: + +```bash +npm install jquery @tsparticles/jquery tsparticles +``` + +导入到你的项目中: + +```javascript +import $ from "jquery"; +import "@tsparticles/jquery"; +``` + +## 引擎初始化 + +在渲染粒子之前,必须使用所需功能初始化 tsParticles 引擎。通过 `$.particles.init` 完成: + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); +})(); +``` + +> **为什么需要这样做?** tsParticles 采用模块化架构。`loadFull` 注册所有内置形状、交互和更新器。你可以导入更小的包(例如 `tsparticles-slim`)来减小打包体积。 + +## 基本使用 + +引擎初始化完毕且 DOM 就绪后,选择一个容器元素并调用 `.particles().load()`: + +```javascript +$(document).ready(async () => { + await $.particles.init(async (engine) => { + const { loadFull } = await import("tsparticles"); + await loadFull(engine); + }); + + $("#tsparticles") + .particles() + .load({ + background: { + color: "#0d47a1", + }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + }, + }); +}); +``` + +容器元素必须存在于 DOM 中: + +```html +
+``` + +## 自定义配置 + +`.load()` 方法接受完整的 `ISourceOptions` 对象。以下是一个综合示例: + +```javascript +$("#tsparticles") + .particles() + .load({ + background: { + color: "#000000", + }, + fpsLimit: 120, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff"], + }, + move: { + direction: "none", + enable: true, + outModes: "bounce", + speed: 4, + }, + number: { + density: { + enable: true, + }, + value: 60, + }, + opacity: { + value: 0.6, + }, + shape: { + type: ["circle", "square", "triangle"], + }, + size: { + value: { min: 2, max: 8 }, + }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + width: 1, + }, + }, + interactivity: { + events: { + onClick: { + enable: true, + mode: "push", + }, + onHover: { + enable: true, + mode: "repulse", + }, + }, + modes: { + push: { + quantity: 4, + }, + repulse: { + distance: 200, + }, + }, + }, + }); +``` + +## 预设加载 + +如果你已安装预设包(例如 `tsparticles-preset-stars`),在引擎初始化时加载它并在配置中引用: + +```bash +npm install tsparticles-preset-stars +``` + +```javascript +(async () => { + await $.particles.init(async (engine) => { + const { loadStarsPreset } = await import("tsparticles-preset-stars"); + await loadStarsPreset(engine); + }); + + $("#tsparticles") + .particles() + .load({ + preset: "stars", + background: { color: "#0d47a1" }, + }); +})(); +``` + +## 事件处理与容器控制 + +`.particles()` 返回一个 jQuery 插件实例。要访问底层的 tsParticles `Container` 并调用 `play()`、`pause()` 或 `destroy()` 等方法: + +```javascript +const $container = $("#tsparticles"); + +// 加载粒子 +$container.particles().load({ + /* 选项 */ +}); + +// 几秒后播放/暂停 +setTimeout(() => { + const container = $container.particles().getContainer(); + container?.pause(); +}, 5000); +``` + +## 完整示例 + +以下是一个完整的、自包含的 HTML 页面,通过 CDN 加载 tsParticles 并呈现带有交互效果的粒子场景: + +```html + + + + + + tsParticles + jQuery + + + +
+ + + + + + + +``` + +## API 参考 + +| 方法 | 描述 | +| ---------------------------------- | --------------------------------------- | +| `$.particles.init(fn)` | 使用加载器回调初始化引擎 | +| `$(el).particles()` | 在元素上创建粒子插件实例 | +| `$(el).particles().load(opts)` | 加载并启动粒子配置 | +| `$(el).particles().destroy()` | 销毁粒子实例并清理 | +| `$(el).particles().getContainer()` | 返回底层的 `Container` 以进行命令式控制 | diff --git a/websites/website/docs/zh/guides/lit.md b/websites/website/docs/zh/guides/lit.md new file mode 100644 index 00000000000..1fc0398aafb --- /dev/null +++ b/websites/website/docs/zh/guides/lit.md @@ -0,0 +1,301 @@ +--- +title: Lit +description: 使用官方 @tsparticles/lit Web 组件封装将 tsParticles 与 Lit 集成。 +--- + +# Lit 集成 + +`@tsparticles/lit` 包提供了一个使用 Lit 构建的 `` 自定义元素,使你能够在任何 Lit 项目或纯 HTML 页面中声明式地使用 tsParticles。 + +## 安装 + +```bash +npm install @tsparticles/lit tsparticles +``` + +该包完全支持 TypeScript,并包含 Lit 的响应式控制器模式,用于响应式更新粒子选项。 + +## 引擎初始化 + +在注册 `` 组件或将其导入应用之前,调用 `initParticlesEngine`。这必须且只执行一次。 + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadFull } from "tsparticles"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +为优化打包体积,只导入项目所需的功能: + +```typescript +import { initParticlesEngine } from "@tsparticles/lit"; +import { loadBasic } from "@tsparticles/basic"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +void initParticlesEngine(async (engine) => { + await loadBasic(engine); + await loadConfettiPreset(engine); +}); +``` + +## 基本使用 + +引擎初始化后,在任何 Lit 模板或 HTML 文件中使用 `` 元素: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private options = { + background: { + color: "#0d1117", + }, + particles: { + number: { value: 60 }, + color: { value: "#58a6ff" }, + links: { + enable: true, + color: "#58a6ff", + }, + move: { enable: true, speed: 2 }, + }, + }; + + render() { + return html` `; + } +} +``` + +`.options` 语法(带前导点)是 Lit 的属性绑定,确保对象通过引用传递,而不是序列化为属性。 + +## 纯 HTML 使用 + +一旦 `@tsparticles/lit` 被打包或加载,该元素也可以在纯 HTML 中使用: + +```html + + + + + + + + + +``` + +你可以将最小选项对象作为 JSON 属性传递: + +```html + +``` + +## 自定义配置 + +将完整的 tsParticles 配置作为 Lit 属性传递: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-particles") +class MyParticles extends LitElement { + @property({ type: Object }) + options: ISourceOptions = { + background: { + color: "#0d1117", + }, + fpsLimit: 120, + fullScreen: { + enable: true, + zIndex: -1, + }, + particles: { + color: { + value: ["#ff5733", "#33ff57", "#3357ff"], + }, + links: { + color: "#ffffff", + enable: true, + opacity: 0.3, + distance: 150, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + }, + number: { + value: 100, + density: { + enable: true, + }, + }, + opacity: { + value: 0.6, + animation: { + enable: true, + speed: 0.5, + minimumValue: 0.1, + }, + }, + size: { + value: { min: 1, max: 5 }, + animation: { + enable: true, + speed: 2, + minimumValue: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { + enable: true, + mode: "grab", + }, + onClick: { + enable: true, + mode: "push", + }, + }, + modes: { + grab: { + distance: 180, + links: { + opacity: 0.5, + }, + }, + push: { + quantity: 4, + }, + }, + }, + }; + + render() { + return html` `; + } +} +``` + +## 事件处理 + +监听 `` 元素触发的 `particles-loaded` 自定义事件: + +```typescript +import { LitElement, html } from "lit"; +import { customElement } from "lit/decorators.js"; +import type { Container } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("my-app") +class MyApp extends LitElement { + private handleParticlesLoaded(e: CustomEvent) { + const container = e.detail; + console.log("粒子已加载:", container); + container?.refresh(); + } + + render() { + return html` `; + } +} +``` + +## TypeScript 示例 + +一个完整的带类型标注的 Lit 元素,包含 `initParticlesEngine`、响应式选项和事件处理: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import { initParticlesEngine } from "@tsparticles/lit"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; +import { loadFull } from "tsparticles"; +import "@tsparticles/lit"; + +void initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +@customElement("particles-background") +class ParticlesBackground extends LitElement { + @property({ type: Object }) + options: ISourceOptions = {}; + + @property({ type: Boolean, attribute: "fullscreen" }) + fullscreen = true; + + protected onParticlesLoaded(e: CustomEvent) { + console.log("容器就绪:", e.detail.id); + } + + render() { + return html` + + + `; + } +} +``` + +## 动态更新 + +由于 `` 使用 Lit 的响应式属性,更改 `options` 属性会自动更新粒子: + +```typescript +import { LitElement, html } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import type { ISourceOptions } from "@tsparticles/engine"; +import "@tsparticles/lit"; + +@customElement("dynamic-particles") +class DynamicParticles extends LitElement { + @state() + private theme: "light" | "dark" = "dark"; + + private get options(): ISourceOptions { + return this.theme === "dark" + ? { + background: { color: "#0d1117" }, + particles: { color: { value: "#58a6ff" } }, + } + : { + background: { color: "#ffffff" }, + particles: { color: { value: "#0969da" } }, + }; + } + + private toggleTheme() { + this.theme = this.theme === "dark" ? "light" : "dark"; + } + + render() { + return html` + + + `; + } +} +``` + +组件会监视 `options` 属性,并在其变化时内部调用 `refresh()`,无缝地在运行时更新粒子配置。 diff --git a/websites/website/docs/zh/guides/nextjs.md b/websites/website/docs/zh/guides/nextjs.md new file mode 100644 index 00000000000..532e860376b --- /dev/null +++ b/websites/website/docs/zh/guides/nextjs.md @@ -0,0 +1,492 @@ +--- +title: Next.js 集成 +description: 将 tsParticles 集成到使用 App Router 的 Next.js 应用中的分步指南。 +--- + +# Next.js 集成 + +本指南涵盖了将 tsParticles 集成到使用 **App Router**(Next.js 13+)的 Next.js 项目中的方法。对于传统的 Pages Router,请参阅底部的 [Legacy Pages Router](#legacy-pages-router) 部分。 + +## 安装 + +安装 `@tsparticles/react` 封装和完整的 `tsparticles` 引擎(或使用 slim 包以减小构建体积): + +```bash +npm install @tsparticles/react tsparticles +``` + +如果你偏好更小的 `@tsparticles/slim` 包: + +```bash +npm install @tsparticles/react @tsparticles/slim +``` + +## 基本使用(App Router) + +Next.js App Router 组件默认在服务端运行。由于 tsParticles 需要浏览器的 `canvas` API,你必须使用 `"use client"` 指令标记组件。 + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesBackground() { + const particlesLoaded = useCallback((container?: Container) => { + console.log("粒子已加载", container); + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }), + [], + ); + + return ; +} +``` + +创建此文件为 `components/particles-background.tsx`,然后导入到任何页面或布局中。由于文件以 `"use client"` 开头,它将在客户端渲染——这正是 tsParticles 需要的位置。 + +## 主题切换 + +通过从当前主题状态派生出选项,将 tsParticles 与 Next.js 主题切换结合: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useMemo, useState, useCallback } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ThemeAwareParticles() { + const [theme, setTheme] = useState<"light" | "dark">("dark"); + + const toggleTheme = useCallback(() => { + setTheme((t) => (t === "dark" ? "light" : "dark")); + }, []); + + const particlesLoaded = useCallback((_container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + background: { + color: theme === "dark" ? "#000000" : "#ffffff", + }, + particles: { + color: { value: theme === "dark" ? "#ffffff" : "#000000" }, + number: { value: 100 }, + links: { + enable: true, + color: theme === "dark" ? "#ffffff" : "#000000", + }, + move: { enable: true }, + }, + }), + [theme], + ); + + return ( + <> + + + + ); +} +``` + +每当 `theme` 变化时,`options` 对象通过 `useMemo` 重新创建,画布会自动更新。 + +## 五彩纸屑效果 + +使用 `@tsparticles/preset-confetti` 在按钮点击等事件上触发庆祝性的五彩纸屑效果: + +```bash +npm install @tsparticles/preset-confetti +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Container, ISourceOptions, Engine } from "@tsparticles/engine"; + +export default function ConfettiButton() { + const [active, setActive] = useState(false); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadConfettiPreset(engine); + }, []); + + const particlesLoaded = useCallback( + async (container?: Container) => { + if (active && container) { + await container.play(); + } + }, + [active], + ); + + const options: ISourceOptions = useMemo( + () => ({ + preset: "confetti", + fullScreen: { zIndex: 1000 }, + }), + [], + ); + + const handleCelebrate = useCallback(() => { + setActive(true); + setTimeout(() => setActive(false), 5000); + }, []); + + return ( + <> + {active && } + + + ); +} +``` + +`init` 回调查在创建粒子之前将五彩纸屑预设加载到引擎中。 + +## 烟花效果 + +同样,烟花预设可以创建壮观的烟花展示: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFireworksPreset } from "@tsparticles/preset-fireworks"; +import type { Container, Engine } from "@tsparticles/engine"; + +export default function FireworksBackground() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFireworksPreset(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options = useMemo( + () => ({ + preset: "fireworks" as const, + fullScreen: { zIndex: -1 }, + background: { + color: "#000", + }, + }), + [], + ); + + return ; +} +``` + +## 带容器引用的完整 TypeScript 示例 + +访问 `Container` 实例以编程方式控制动画(播放、暂停、销毁、导出图片): + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useRef } from "react"; +import { loadFull } from "tsparticles"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +export default function ControllableParticles() { + const containerRef = useRef(undefined); + + const particlesInit = useCallback(async (engine: Engine) => { + await loadFull(engine); + }, []); + + const particlesLoaded = useCallback((container?: Container) => { + containerRef.current = container; + }, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + fpsLimit: 120, + interactivity: { + events: { + onClick: { enable: true, mode: "push" }, + onHover: { enable: true, mode: "repulse" }, + }, + modes: { + push: { quantity: 4 }, + repulse: { distance: 100 }, + }, + }, + particles: { + color: { value: "#ff0000" }, + links: { + enable: true, + color: "#ff0000", + distance: 150, + }, + move: { enable: true, speed: 2 }, + number: { value: 60 }, + size: { value: { min: 1, max: 5 } }, + }, + }), + [], + ); + + const handlePause = useCallback(() => { + containerRef.current?.pause(); + }, []); + + const handlePlay = useCallback(() => { + containerRef.current?.play(); + }, []); + + return ( +
+ +
+ + +
+
+ ); +} +``` + +关键点: + +- `particlesInit` 加载引擎功能(每个组件挂载只运行一次)。 +- `particlesLoaded` 在容器完全初始化时触发。 +- `containerRef` 保存 `Container` 实例,以便稍后调用其方法。 + +## 性能优化:useMemo 和 useCallback + +始终将静态或少变化的选项包裹在 `useMemo` 中,将事件处理函数包裹在 `useCallback` 中,以防止画布不必要的重新渲染: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo, useState } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function PerformanceExample() { + const [particlesCount, setParticlesCount] = useState(80); + + // 稳定的回调——除非依赖项变化,否则不会重新创建 + const particlesLoaded = useCallback((container?: Container) => { + console.log("容器就绪", container?.id); + }, []); + + // 稳定的选项对象——防止画布重新初始化 + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: particlesCount }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [particlesCount], + ); + + return ( +
+ + +
+ ); +} +``` + +如果没有这些优化,每次父组件重新渲染都会创建新的 `options` 对象,导致画布被重新创建。 + +## 页面集成 + +将粒子背景添加到页面布局中,而不影响页面内容: + +```tsx +// app/layout.tsx(服务端组件) +import dynamic from "next/dynamic"; + +const ParticlesBackground = dynamic(() => import("@/components/particles-background"), { ssr: false }); + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + +
{children}
+ + + ); +} +``` + +使用 `dynamic()` 配合 `ssr: false` 确保组件永远不会在服务端渲染期间运行。粒子画布通过 CSS `z-index` 位于主内容之后。 + +## 多个实例 + +你可以在同一页面渲染多个独立的 `Particles` 组件,每个组件有自己的配置: + +```tsx +"use client"; + +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +function ParticlesGallery() { + const loaded = useCallback((c?: Container) => {}, []); + + const redOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#1a0000" }, + particles: { + color: { value: "#ff0000" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + const blueOptions: ISourceOptions = useMemo( + () => ({ + fullScreen: false, + height: 200, + background: { color: "#00001a" }, + particles: { + color: { value: "#0000ff" }, + number: { value: 30 }, + move: { enable: true }, + }, + }), + [], + ); + + return ( +
+ + +
+ ); +} +``` + +每个 `Particles` 组件创建一个独立的画布,拥有自己的动画循环。设置 `fullScreen: false` 并为每个组件指定固定高度,使它们共存于文档流中。 + +## Legacy Pages Router + +如果你使用的是 Next.js **Pages Router**(`pages/` 目录),方法类似但不需要 `"use client"` 指令。相反,你可以在页面组件中使用动态导入: + +```tsx +// pages/index.tsx +import dynamic from "next/dynamic"; +import type { NextPage } from "next"; + +const ParticlesComponent = dynamic(() => import("../components/particles-component"), { ssr: false }); + +const Home: NextPage = () => { + return ( +
+ +

欢迎

+
+ ); +}; + +export default Home; +``` + +组件本身(`components/particles-component.tsx`)是一个纯 React 组件: + +```tsx +import Particles from "@tsparticles/react"; +import { useCallback, useMemo } from "react"; +import type { Container, ISourceOptions } from "@tsparticles/engine"; + +export default function ParticlesComponent() { + const particlesLoaded = useCallback((container?: Container) => {}, []); + + const options: ISourceOptions = useMemo( + () => ({ + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 80 }, + links: { enable: true }, + move: { enable: true }, + }, + }), + [], + ); + + return ; +} +``` + +请注意,Pages Router **不**需要 `"use client"`,因为页面组件默认已在客户端渲染。 + +## 故障排除 + +| 症状 | 原因 | 解决方法 | +| -------------- | ---------------------------- | -------------------------------------------------------- | +| 空白白屏 | SSR 渲染了依赖 canvas 的模块 | 使用 `dynamic(..., { ssr: false })` 或包裹在客户端组件中 | +| 画布不显示 | 容器高度为零 | 设置 `fullScreen: { zIndex: -1 }` 或指定明确尺寸 | +| 选项更改未反映 | 未创建新的对象引用 | 使用带正确依赖数组的 `useMemo` | +| 预设不生效 | 容器初始化前未加载预设 | 在 `init` 回调中调用 `loadXPreset(engine)` | + +## 下一步 + +- 浏览[交互式演示](/demos/)以获取现成的配置。 +- 阅读完整的[选项参考](/options/)了解每个可用参数。 +- 查看[预设](/demos/presets)页面获取更多预构建预设,如雪花、星星和萤火虫。 diff --git a/websites/website/docs/zh/guides/nuxt.md b/websites/website/docs/zh/guides/nuxt.md new file mode 100644 index 00000000000..4fa446db05b --- /dev/null +++ b/websites/website/docs/zh/guides/nuxt.md @@ -0,0 +1,463 @@ +--- +title: Nuxt 集成 +description: 将 tsParticles 集成到 Nuxt 3 / Nuxt 4 应用中的分步指南。 +--- + +# Nuxt 集成 + +本指南涵盖了使用官方 `@tsparticles/vue3` 封装将 tsParticles 集成到 **Nuxt 3**(及 Nuxt 4)项目中的方法。Nuxt 同时在服务端和客户端运行,因此你必须保护粒子组件免受 SSR 的影响。 + +## 安装 + +安装 Vue 3 封装和你选择的引擎包: + +```bash +npm install @tsparticles/vue3 tsparticles +``` + +为了更小的打包体积,请安装 `@tsparticles/slim` 而不是 `tsparticles`: + +```bash +npm install @tsparticles/vue3 @tsparticles/slim +``` + +## 基本使用 + +Nuxt 默认在服务端渲染组件。由于 tsParticles 需要浏览器的 `canvas` API,你必须将 `` 组件包裹在 `` 标签中: + +```vue + + + + + +``` + +`` 包装器确保 `` 组件仅在浏览器中挂载,防止水合不匹配。 + +## 配置 + +使用完整的 `ISourceOptions` 类型进行类型安全的配置。你可以内联定义选项或从单独的配置文件导入: + +```vue + +``` + +## 下雪效果 + +使用雪花预设创建冬日飘雪效果: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +由于预设是在 ` +``` + +可用的交互模式包括:`grab`、`bubble`、`connect`、`repulse`、`push`、`remove`、`attract` 和 `slow`。 + +## 事件处理 + +`` 组件会触发多个生命周期事件: + +```vue + + + +``` + +| 事件 | 负载类型 | 描述 | +| -------------------- | ----------- | -------------------------------- | +| `@particles-init` | `Engine` | tsParticles 引擎初始化时触发一次 | +| `@particles-loaded` | `Container` | 容器完成加载或重新加载时触发 | +| `@particles-destroy` | 无 | 容器销毁时触发 | + +## 完整 TypeScript 示例 + +一个完整的、带类型标注的组件,包含显式导入和生命周期感知: + +```vue + + + + + +``` + +## 页面集成 + +通过在页面的模板中放置组件,将粒子背景添加到特定的 Nuxt 页面: + +```vue + + + + + +``` + +如果你希望粒子出现在**每个**页面上,请将组件添加到 `layouts/default.vue` 而不是单个页面。 + +## Nuxt 4 说明 + +Nuxt 4 保持与 Nuxt 3 的 `` 和 ` +``` + +## 故障排除 + +| 症状 | 原因 | 解决方法 | +| --------------------- | ------------------------------ | --------------------------------------------------------- | +| 黑屏 / 水合错误 | `` 在服务端渲染 | 包裹在 `` 中 | +| 预设无效果 | 组件挂载前未加载预设 | 在 ` + +``` + +引擎初始化一次,并在应用中所有 `` 实例之间共享。 + +--- + +## 基本使用 + +初始化引擎后,在模板中使用 `` 组件。将配置作为 JSON 字符串化的选项对象或组件属性的引用传递。 + +```html + + + + + +``` + +--- + +## 条件渲染 + +使用 Riot 的 `if={}` 指令配合状态属性来延迟渲染粒子组件,直到引擎完成初始化。这可以避免布局偏移,并确保组件接收到准备好的引擎。 + +```html + + + + + +``` + +调用 `this.update()` 会触发重新渲染,因此在 Promise 解析后 `` 标签就会出现。 + +--- + +## 预设使用 + +`@tsparticles/configs` 包为常见效果(如五彩纸屑、烟花、雪花和星星)提供了预构建配置。直接用作你的选项对象。 + +```html + + + + + +``` + +可用的预设包括 `basic`、`confetti`、`fireworks`、`snow`、`stars` 等。每个预设都需要在引擎回调中加载相应的预设包。例如,`configs.fireworks` 需要 `loadFireworksPreset`。 + +--- + +## 自定义配置 + +构建一个包含交互功能、多种形状和高级动画选项的自定义配置。 + +```html + + + + + +``` + +--- + +## 完整组件 + +以下是一个完整的 `.riot` 文件,将所有内容整合在一起:`onBeforeMount` 中的引擎初始化、带状态的条件渲染、丰富的交互配置以及通过组件内置支持的加载事件的 `particlesLoaded` 回调。 + +```html + +
+

tsParticles + Riot.js

+ + {#if state.particlesInitialized} + + {:else} +

正在加载粒子引擎...

+ {/if} +
+ + + + +
+``` + +--- + +你现在已拥有将 tsParticles 集成到 Riot.js 应用所需的全部内容。每个示例都是独立的,可直接复制到你的项目中。 diff --git a/websites/website/docs/zh/guides/solid.md b/websites/website/docs/zh/guides/solid.md new file mode 100644 index 00000000000..0ce8ce95a4f --- /dev/null +++ b/websites/website/docs/zh/guides/solid.md @@ -0,0 +1,511 @@ +--- +title: SolidJS 集成 +description: 使用官方 @tsparticles/solid 封装将 tsParticles 集成到 SolidJS 应用中的分步指南。 +--- + +# SolidJS 集成 + +本指南涵盖了使用官方 `@tsparticles/solid` 封装将 tsParticles 集成到 **SolidJS** 项目中的方法。SolidJS 的细粒度响应式模型与 tsParticles 配合良好——选项更改会触发针对性的画布更新,无需完全重新初始化。 + +## 安装 + +安装 SolidJS 封装和你选择的引擎包: + +```bash +npm install @tsparticles/solid tsparticles +``` + +为了更小的打包体积,使用 `@tsparticles/slim` 替代: + +```bash +npm install @tsparticles/solid @tsparticles/slim +``` + +## 基本使用 + +SolidJS 完全在浏览器中运行(无 SSR),因此你不需要防范服务端渲染。但是,引擎必须在渲染粒子之前异步初始化。 + +在 `onMount` 中使用 `initParticlesEngine` 加载引擎功能,然后使用 `` 条件渲染 `` 组件: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [initialized, setInitialized] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setInitialized(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true }, + size: { value: 3 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +`` 组件确保 `` 元素仅在引擎就绪后才插入 DOM。 + +## 引擎初始化 + +`initParticlesEngine` 函数接受一个接收 `Engine` 实例的回调。使用此回调注册配置所需的功能: + +```tsx +import { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import { loadSlim } from "@tsparticles/slim"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; +import type { Engine } from "@tsparticles/engine"; + +// 最小化——仅基础形状和移动 +initParticlesEngine((engine: Engine) => loadSlim(engine)).then(() => { + console.log("引擎就绪(slim)"); +}); + +// 完整——包含所有功能 +initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => { + console.log("引擎就绪(full)"); +}); + +// 仅预设——只需特定预设所需的功能 +initParticlesEngine((engine: Engine) => loadConfettiPreset(engine)).then(() => { + console.log("五彩纸屑预设已加载"); +}); +``` + +在应用中调用一次 `initParticlesEngine`——通常在根组件的 `onMount` 中。引擎实例会被缓存,因此后续调用会立即返回。 + +## 条件渲染 + +使用 SolidJS 的 `` 控制流来延迟渲染,直到引擎初始化完成: + +```tsx +import { createSignal, Show, onMount } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import { loadFull } from "tsparticles"; +import type { Engine } from "@tsparticles/engine"; +import type { Component } from "solid-js"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + 正在加载粒子...

}> + +
+ ); +}; +``` + +`fallback` 属性在引擎初始化时显示加载指示器。 + +## 预设使用 + +使用 `@tsparticles/configs` 快速获得预设计的配置: + +```bash +npm install @tsparticles/configs +``` + +```tsx +import configs from "@tsparticles/configs"; +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + return ( + +
+ + +
+
+ ); +}; + +export default App; +``` + +可用的配置包括:`basic`、`bubbles`、`snow`、`stars`、`fireworks`、`confetti`、`links` 等。 + +## 交互式粒子 + +通过配置 `interactivity` 部分添加点击和悬停交互: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + particles: { + number: { value: 60 }, + links: { enable: true, distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 4 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 200, links: { opacity: 0.5 } }, + push: { quantity: 4 }, + }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +- **悬停模式**:`grab`、`bubble`、`repulse`、`attract`、`slow`、`connect` +- **点击模式**:`push`、`remove`、`repulse`、`bubble`、`attract`、`pause` + +## 自定义配置 + +一个完整的自定义配置,包含多种粒子形状、颜色调色板和运动设置: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#0a0a23" }, + fpsLimit: 60, + particles: { + color: { + value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"], + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + straight: false, + outModes: "bounce", + attract: { enable: true, rotateX: 600, rotateY: 1200 }, + }, + number: { + value: 40, + density: { enable: true }, + }, + opacity: { + value: { min: 0.3, max: 0.8 }, + animation: { + enable: true, + speed: 0.5, + sync: false, + }, + }, + size: { + value: { min: 2, max: 8 }, + animation: { + enable: true, + speed: 2, + sync: false, + }, + }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.3, + width: 1, + }, + shape: { + type: ["circle", "square", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + twinkle: { + particles: { + enable: true, + frequency: 0.05, + opacity: 1, + }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "bubble" }, + }, + modes: { + repulse: { distance: 120 }, + bubble: { distance: 200, size: 10, opacity: 0.8 }, + }, + }, + detectRetina: true, + }; + + return ( + + + + ); +}; + +export default App; +``` + +## 完整 TypeScript 示例 + +一个完整的带类型标注的组件,包含容器引用、引擎初始化和手动控制: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [container, setContainer] = createSignal(undefined); + const [paused, setPaused] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadFull(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + fullScreen: { zIndex: -1 }, + background: { color: "#1a1a2e" }, + particles: { + color: { value: "#e94560" }, + number: { value: 80 }, + links: { enable: true, color: "#e94560", distance: 150 }, + move: { enable: true, speed: 2 }, + size: { value: { min: 1, max: 5 } }, + }, + }; + + const particlesLoaded = (c: Container) => { + setContainer(c); + }; + + const togglePause = () => { + const c = container(); + if (c) { + if (paused()) { + c.play(); + } else { + c.pause(); + } + setPaused(!paused()); + } + }; + + return ( + + + + + ); +}; + +export default App; +``` + +## 使用信号的动态选项 + +SolidJS 的优势之一是细粒度响应式——你可以使用信号驱动粒子选项,画布将高效更新: + +```tsx +import { loadFull } from "tsparticles"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + const [color, setColor] = createSignal("#ff0000"); + const [particleCount, setParticleCount] = createSignal(60); + + onMount(() => { + initParticlesEngine((engine: Engine) => loadFull(engine)).then(() => setReady(true)); + }); + + // options 是一个普通对象——通过 Particles 组件的内部跟踪进行响应式读取 + const options = (): ISourceOptions => ({ + fullScreen: { zIndex: -1 }, + background: { color: "#000" }, + particles: { + color: { value: color() }, + number: { value: particleCount() }, + links: { enable: true, color: color() }, + move: { enable: true }, + }, + }); + + return ( + + {}} /> +
+ + +
+
+ ); +}; + +export default App; +``` + +由于 `options` 是一个访问信号的函数,每次 `color()` 或 `particleCount()` 发生变化时,`` 组件都会接收到新的选项对象,并仅将更改的属性应用到现有画布。 + +## 预设与自定义覆盖 + +加载预设,然后合并自定义覆盖以实现定制效果: + +```tsx +import { loadSnowPreset } from "@tsparticles/preset-snow"; +import { createSignal, Show, onMount } from "solid-js"; +import type { Component } from "solid-js"; +import Particles, { initParticlesEngine } from "@tsparticles/solid"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; + +const App: Component = () => { + const [ready, setReady] = createSignal(false); + + onMount(() => { + initParticlesEngine(async (engine: Engine) => { + await loadSnowPreset(engine); + }).then(() => setReady(true)); + }); + + const options: ISourceOptions = { + preset: "snow", + fullScreen: { zIndex: -1 }, + background: { color: "#0d0d2b" }, + particles: { + // 将雪花颜色覆盖为蓝色 + color: { value: "#88ccff" }, + // 增加雪花数量 + number: { value: 300 }, + }, + }; + + return ( + + + + ); +}; + +export default App; +``` + +预设为每个选项提供默认值,你的覆盖值会合并到其上——你只需指定要更改的属性。 + +## 故障排除 + +| 症状 | 原因 | 解决方法 | +| -------------- | ------------------------------------ | ------------------------------------------------------------------- | +| 空白 DOM 元素 | 渲染前引擎未初始化 | 将 `` 包裹在 `` 中 | +| 没有可见粒子 | 缺少 `move.enable` 或 `number.value` | 确保 `particles.move.enable: true` 且 `particles.number.value > 0` | +| 画布在内容后面 | fullScreen 缺少 `zIndex` | 使用 `fullScreen: { zIndex: -1 }` | +| 选项更改未反映 | 对象引用未更改 | 将选项包裹在函数或 store 中;避免使用静态对象 | +| 引擎未找到 | 缺少 `loadFull` 或 `loadSlim` 导入 | 安装 `tsparticles` 或 `@tsparticles/slim` 并调用 `loadFull(engine)` | + +## 下一步 + +- 探索[配置游乐场](/playground/configs)以获取现成的配置。 +- 阅读[选项参考](/options/)以获取完整的参数列表。 +- 在 GitHub 上浏览 [SolidJS 源码](https://github.com/tsparticles/solid) 了解封装内部实现。 diff --git a/websites/website/docs/zh/guides/stencil.md b/websites/website/docs/zh/guides/stencil.md new file mode 100644 index 00000000000..6c82afd8d6c --- /dev/null +++ b/websites/website/docs/zh/guides/stencil.md @@ -0,0 +1,359 @@ +--- +title: Stencil 指南 +description: 将 tsParticles 与 Stencil 组件集成的完整指南。 +--- + +# Stencil 指南 + +## 目录 + +1. [安装](#installation) +2. [自定义元素注册](#custom-elements-registration) +3. [基本使用](#basic-usage) +4. [引擎初始化](#engine-initialization) +5. [自定义配置](#custom-configuration) +6. [组件生命周期](#component-lifecycle) +7. [TypeScript 示例](#typescript-example) + +--- + +## 安装 + +通过 npm 安装 Stencil 封装和 tsParticles 引擎: + +```bash +npm install @tsparticles/stencil tsparticles +``` + +可选安装预设包以减少手动配置: + +```bash +npm install @tsparticles/slim +``` + +--- + +## 自定义元素注册 + +`@tsparticles/stencil` 包提供了一个 `defineCustomElements` 函数,用于向浏览器注册 `` 自定义元素。在应用中使用该组件之前调用一次。 + +```tsx +import { defineCustomElements } from "@tsparticles/stencil/loader"; + +// 注册 元素 +defineCustomElements(); +``` + +对于使用懒加载的 Stencil 项目,在 `componentWillLoad` 或应用根组件中调用此函数,以确保元素在渲染前可用。 + +--- + +## 基本使用 + +自定义元素注册后,你可以在 JSX 中使用 ``,并传入 `options` 属性和 `init` 回调来加载所需的引擎功能。 + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const options: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { value: 80 }, + color: { value: "#00d4ff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 2, max: 5 } }, + links: { + enable: true, + distance: 150, + color: "#00d4ff", + opacity: 0.3, + width: 1, + }, + move: { + enable: true, + speed: 1.5, + direction: "none", + random: true, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#0d1117" }, +}; + +@Component({ tag: "my-particles" }) +export class MyParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## 引擎初始化 + +`init` 属性接收引擎实例,让你加载所需功能。这是调用 `loadSlim`、`loadFull` 或单个更新器/交互插件推荐的位置。 + +```tsx +import { loadSlim } from "@tsparticles/slim"; +import { loadFull } from "tsparticles"; +import { loadConfettiPreset } from "@tsparticles/preset-confetti"; + +// 选项 A:轻量级(圆形、基础移动、连线) +init={async engine => { await loadSlim(engine); }} + +// 选项 B:完整功能集(所有形状、效果、预设) +init={async engine => { await loadFull(engine); }} + +// 选项 C:预设(五彩纸屑、烟花、雪花、星星) +init={async engine => { await loadConfettiPreset(engine); }} +``` + +引擎实例在初始化后也可以通过 `container-id` 属性访问,允许你在需要时以编程方式控制粒子系统。 + +--- + +## 自定义配置 + +以下是一个包含交互功能、多种形状类型和悬停/点击模式的完整配置。 + +```tsx +import { Component, h } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +const fullOptions: ISourceOptions = { + fpsLimit: 60, + particles: { + number: { + value: 60, + density: { enable: true, width: 800, height: 800 }, + }, + color: { + value: ["#ff6b6b", "#feca57", "#48dbfb", "#ff9ff3", "#54a0ff"], + }, + shape: { + type: ["circle", "triangle", "polygon"], + options: { + polygon: { sides: 6 }, + }, + }, + opacity: { value: { min: 0.4, max: 0.8 } }, + size: { value: { min: 3, max: 8 } }, + links: { + enable: true, + distance: 200, + color: "#ffffff", + opacity: 0.15, + width: 1, + }, + move: { + enable: true, + speed: 2, + direction: "none", + random: true, + straight: false, + outModes: { default: "out" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "attract" }, + onClick: { enable: true, mode: "repulse" }, + }, + modes: { + attract: { distance: 200, duration: 0.4, factor: 1 }, + repulse: { distance: 200, duration: 0.4 }, + }, + }, + background: { + color: "#0f0f23", + }, +}; + +@Component({ tag: "app-particles" }) +export class AppParticles { + render() { + return ( + { + await loadSlim(engine); + }} + /> + ); + } +} +``` + +--- + +## 组件生命周期 + +在 Stencil 中,推荐的用于一次性设置的 lifecycle 钩子是 `componentWillLoad`。使用它来注册自定义元素并管理初始化状态,以便 `` 组件仅在引擎准备就绪时渲染。 + +```tsx +import { Component, h, State } from "@stencil/core"; +import type { ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ tag: "app-root" }) +export class AppRoot { + @State() private engineReady = false; + + private options: ISourceOptions = { + particles: { + number: { value: 50 }, + color: { value: "#ffffff" }, + shape: { type: "circle" }, + opacity: { value: 0.6 }, + size: { value: { min: 1, max: 4 } }, + move: { + enable: true, + speed: 1, + outModes: { default: "bounce" }, + }, + }, + background: { color: "#1a1a2e" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.engineReady = true; + } + + render() { + return ( +
+

tsParticles + Stencil

+ {this.engineReady && ( + { + await loadSlim(engine); + }} + /> + )} +
+ ); + } +} +``` + +使用 `@State()` 确保组件在引擎就绪时重新渲染,条件渲染防止粒子容器在自定义元素定义之前挂载。 + +--- + +## TypeScript 示例 + +以下是一个完整的、带类型标注的 Stencil 应用组件,使用 slim 预设、悬停交互功能和自定义深色主题集成了 tsParticles。 + +```tsx +import { Component, h, State, Prop } from "@stencil/core"; +import type { Container, Engine, ISourceOptions } from "@tsparticles/engine"; +import { defineCustomElements } from "@tsparticles/stencil/loader"; +import { loadSlim } from "@tsparticles/slim"; + +@Component({ + tag: "app-home", + styleUrl: "app-home.css", + shadow: true, +}) +export class AppHome { + @State() private initialized = false; + + @Prop() readonly title: string = "欢迎"; + + private container?: Container; + + private readonly options: ISourceOptions = { + fullScreen: { enable: true, zIndex: -1 }, + fpsLimit: 60, + particles: { + number: { value: 80, density: { enable: true } }, + color: { value: "#6366f1" }, + shape: { type: "circle" }, + opacity: { value: { min: 0.3, max: 0.7 } }, + size: { value: { min: 2, max: 6 } }, + links: { + enable: true, + distance: 160, + color: "#6366f1", + opacity: 0.25, + width: 1, + }, + move: { + enable: true, + speed: 1.2, + direction: "none", + random: false, + straight: false, + outModes: { default: "bounce" }, + }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "grab" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + grab: { distance: 180, links: { opacity: 0.6 } }, + push: { quantity: 3 }, + }, + }, + background: { color: "#0a0a1a" }, + }; + + componentWillLoad() { + defineCustomElements(); + this.initialized = true; + } + + private handleInit = async (engine: Engine): Promise => { + await loadSlim(engine); + }; + + private handleLoaded = async (container?: Container): Promise => { + this.container = container; + console.log("粒子容器已加载:", container?.id); + }; + + render() { + return ( +
+

{this.title}

+

由 tsParticles 和 Stencil 驱动

+ + {this.initialized && ( + + )} +
+ ); + } +} +``` + +`particlesLoaded` 事件在第一帧渲染完成后触发,让你可以访问 `Container` 实例以进行程序化控制(播放、暂停、停止、切换主题)。 + +--- + +你现在已拥有将 tsParticles 集成到 Stencil 应用所需的全部内容。每个示例都是独立的,可直接复制到你的项目中。 diff --git a/websites/website/docs/zh/guides/svelte.md b/websites/website/docs/zh/guides/svelte.md new file mode 100644 index 00000000000..540f0492d5f --- /dev/null +++ b/websites/website/docs/zh/guides/svelte.md @@ -0,0 +1,580 @@ +--- +title: Svelte 集成 +description: 使用 @tsparticles/svelte 将 tsParticles 集成到 Svelte 和 SvelteKit 应用中的分步指南。 +--- + +# Svelte 集成 + +`@tsparticles/svelte` 包为 tsParticles 提供了一个原生的 Svelte 组件。本指南涵盖 Svelte(配合 Vite)和 SvelteKit,包括响应式选项、事件处理和多个实例。 + +--- + +## 安装 + +```bash +npm install @tsparticles/svelte @tsparticles/engine +``` + +如需完整包或预设: + +```bash +npm install tsparticles +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +``` + +--- + +## 基本使用 + +```svelte + + + +``` + +--- + +## 引擎初始化 + +传递一个 `on:init` 事件处理程序来加载应用所需的插件和预设: + +```svelte + + + +``` + +或者,在挂载前使用 `initParticlesEngine` 工具函数: + +```svelte + + +{#if ready} + +{/if} +``` + +--- + +## 下雪效果 + +```bash +npm install @tsparticles/preset-snow +``` + +```svelte + + + +``` + +通过合并额外选项自定义预设行为: + +```svelte + +``` + +--- + +## 星星效果 + +```bash +npm install @tsparticles/preset-stars +``` + +```svelte + + + +``` + +--- + +## 交互式粒子 + +添加鼠标悬停和点击交互: + +```svelte + + + +``` + +--- + +## 事件处理 + +```svelte + + +
+ + + +
+ + +``` + +| 事件 | 详情 | 触发时机 | +| -------------------- | ----------- | ---------------- | +| `on:init` | `Engine` | 引擎初始化之后 | +| `on:particlesLoaded` | `Container` | 容器完全就绪之后 | + +--- + +## TypeScript 示例 + +完整的带类型标注的组件: + +```svelte + + + +``` + +--- + +## 动态选项 + +响应式选项更新粒子而无需重新创建实例: + +```svelte + + +
+ +
+ + +``` + +`$:` 响应式声明在 `color` 变化时重新计算 `options`,而 `Particles` 组件会自动接收新的配置。 + +--- + +## 多个实例 + +在同一页面渲染多个独立的粒子系统: + +```svelte + + +
+
+ +
+
+ +
+
+``` + +每个 `` 组件拥有自己的 `id`、画布和引擎上下文。 + +--- + +## SvelteKit 使用 + +在 SvelteKit 中,画布需要浏览器环境。禁用组件的 SSR: + +```svelte + + +{#if Component} + +{/if} +``` + +或者将导入包装在仅客户端组件中。对于 SvelteKit 2+,你也可以使用 `vite-plugin-svelte` 的 SSR 排除项。 + +--- + +## API 参考 + +| 属性 | 类型 | 默认值 | 描述 | +| --------- | ---------------- | --------------- | -------------------- | +| `id` | `string` | `"tsparticles"` | 画布元素 ID | +| `options` | `ISourceOptions` | `{}` | 粒子配置对象 | +| `url` | `string` | — | 远程 JSON 配置的 URL | + +| 事件 | 详情 | 描述 | +| -------------------- | ----------- | -------------------------------- | +| `on:init` | `Engine` | 引擎初始化时触发(用于加载插件) | +| `on:particlesLoaded` | `Container` | 容器完全就绪时触发 | + +--- + +## 故障排除 + +- **画布不可见** — 确保父容器有明确尺寸(`height: 100%`、`height: 100vh` 或固定像素值)。 +- **`loadFull is not a function`** — 确认已安装 `tsparticles`,并且你从 `tsparticles`(而非 `@tsparticles/engine`)导入 `loadFull`。 +- **响应式不生效** — 确保 `options` 是一个响应式变量(`$:` 或绑定到响应式源的 `let`)。普通的 `const` 值不会更新。 +- **SvelteKit 黑屏** — 动态导入 `@tsparticles/svelte` 或使用如上 SvelteKit 部分所示的 `browser` 守卫。 +- **`event.detail` 的 TypeScript 错误** — 对事件处理程序使用 `CustomEvent` 和 `CustomEvent` 类型。 diff --git a/websites/website/docs/zh/guides/vanilla.md b/websites/website/docs/zh/guides/vanilla.md new file mode 100644 index 00000000000..b3139d4f9db --- /dev/null +++ b/websites/website/docs/zh/guides/vanilla.md @@ -0,0 +1,889 @@ +--- +title: Vanilla JS 指南 +description: 使用纯 JavaScript 集成 tsParticles 的完整指南。 +--- + +# Vanilla JS 指南 + +## 目录 + +1. [快速入门](#getting-started) +2. [基础粒子效果](#basic-particles) +3. [五彩纸屑效果](#confetti-effect) +4. [烟花效果](#fireworks-effect) +5. [彩带效果](#ribbons-effect) +6. [雪花效果](#snow-effect) +7. [网络/连线效果](#network-links-effect) +8. [星空效果](#stars-effect) +9. [自定义配置](#custom-configuration) +10. [多个容器](#multiple-containers) +11. [动态控制](#dynamic-controls) + +--- + +## 快速入门 + +### CDN(快速开始) + +在 HTML 中添加一个 `
` 占位符和 script 标签。你至少需要引擎 + 一个包,并且在 `tsParticles.load()` 之前调用加载器。 + +```html + + + + + + tsParticles – Getting Started + + + +
+ + + + + + +``` + +### npm + +```bash +npm install @tsparticles/engine @tsparticles/slim +``` + +然后导入并使用: + +```javascript +import { tsParticles } from "@tsparticles/engine"; +import { loadSlim } from "@tsparticles/slim"; + +(async () => { + await loadSlim(tsParticles); + + await tsParticles.load({ + id: "tsparticles", + options: { + /* ... */ + }, + }); +})(); +``` + +> **注意:** 仅 `@tsparticles/engine` 不会绘制任何内容。你必须安装一个包(推荐 `@tsparticles/slim`)或单独的插件才能显示可见的形状。 + +--- + +## 基础粒子效果 + +一个最小配置,渲染 100 个圆形粒子,随机颜色和温和的运动。在 v4 中,粒子颜色通过 `paint` 而非旧的 `color` 属性设置。 + +```html + + + + + + Basic Particles + + + +
+ + + + + + +``` + +--- + +## 五彩纸屑效果 + +使用专用的 `@tsparticles/confetti` 包,通过单个函数调用实现庆祝性的爆发效果。 + +```html + + + + + + Confetti + + + + + + + + + +``` + +--- + +## 烟花效果 + +使用专用的 `@tsparticles/fireworks` 包带音效的烟花展示。 + +```html + + + + + + Fireworks + + + + + + + +``` + +--- + +## 彩带效果 + +使用专用的 `@tsparticles/ribbons` 包实现随鼠标位置流动的彩带动画。 + +```html + + + + + + Ribbons + + + + + + + +``` + +--- + +## 雪花效果 + +使用 `@tsparticles/configs` 预设目录实现的柔和飘落雪花效果。 + +```html + + + + + + Snow Effect + + + +
+ + + + + + + +``` + +或者,使用独立的预设包: + +```html + + + + +``` + +--- + +## 网络/连线效果 + +带有鼠标交互的经典连接节点视觉效果。`@tsparticles/slim` 包包含连线交互和鼠标抓取模式。 + +```html + + + + + + Network / Links + + + +
+ + + + + + +``` + +--- + +## 星空效果 + +使用 `@tsparticles/configs` 预设目录实现的星空夜景。 + +```html + + + + + + Stars Effect + + + +
+ + + + + + + +``` + +或者,使用独立的预设包: + +```html + + + + +``` + +--- + +## 自定义配置 + +使用 slim 包从零构建一个带有渐变背景、交互式悬停效果和多种形状类型的配置。 + +```html + + + + + + Custom Config + + + +

Custom Configuration

+
+ + + + + + +``` + +--- + +## 多个容器 + +在同一页面上运行多个独立的粒子实例,每个实例具有各自的配置。 + +```html + + + + + + Multiple Containers + + + +
+
+
+
+ + + + + + +``` + +--- + +## 动态控制 + +在运行时以编程方式启动、停止、暂停和切换主题。 + +```html + + + + + + Dynamic Controls + + + +
+
+ + + + + + +
+ + + + + + +``` + +--- + +你现在已经涵盖了 tsParticles v4 的每一个主要 Vanilla JS 集成模式。每个示例都是一个独立的 HTML 文件,你可以在浏览器中打开它以查看 tsParticles 的实际效果。 diff --git a/websites/website/docs/zh/guides/vue3.md b/websites/website/docs/zh/guides/vue3.md new file mode 100644 index 00000000000..d059905bd60 --- /dev/null +++ b/websites/website/docs/zh/guides/vue3.md @@ -0,0 +1,622 @@ +--- +title: Vue 3 集成 +description: 使用 @tsparticles/vue3 将 tsParticles 集成到 Vue 3 应用中的分步指南。 +--- + +# Vue 3 集成 + +`@tsparticles/vue3` 包为 tsParticles 提供了原生的 Vue 3 组件和插件系统。本指南涵盖从基本设置到高级模式(如动态主题切换和自定义预设)的所有内容。 + +--- + +## 安装 + +```bash +npm install @tsparticles/vue3 @tsparticles/engine +``` + +可选安装预设或完整包: + +```bash +# 完整包(所有功能) +npm install tsparticles + +# 特定预设 +npm install @tsparticles/preset-confetti +npm install @tsparticles/preset-fireworks +npm install @tsparticles/preset-snow +npm install @tsparticles/preset-stars + +# 工具配置 +npm install @tsparticles/configs +``` + +--- + +## 基本使用 + +在应用入口注册插件,然后在任何地方使用 `` 组件。 + +### 应用入口(`main.ts`) + +```typescript +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +const app = createApp(App); + +app.use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, +}); + +app.mount("#app"); +``` + +### 组件(`App.vue`) + +```vue + + + +``` + +--- + +## 在组件中使用 `particlesInit` + +如果你不希望使用全局插件,直接传递 `init` 回调: + +```vue + + + +``` + +--- + +## 事件 + +组件会触发多个生命周期事件: + +```vue + + + +``` + +--- + +## 五彩纸屑效果 + +使用五彩纸屑预设进行庆祝: + +```bash +npm install @tsparticles/preset-confetti +``` + +```vue + + + +``` + +对于一次性爆发效果,可加载预设后在方法内部以编程方式调用 `tsParticles.load()`。 + +--- + +## 烟花效果 + +烟花预设可创建高冲击力的粒子爆炸效果: + +```bash +npm install @tsparticles/preset-fireworks +``` + +```vue + + + +``` + +> **提示:** 烟花预设消耗资源较多。通过切换绑定到组件的 `v-if`,在用户交互(如按钮点击)时触发。 + +--- + +## 下雪效果 + +使用雪花预设模拟下雪: + +```bash +npm install @tsparticles/preset-snow +``` + +```vue + + + +``` + +--- + +## 交互式粒子 + +添加悬停和点击交互模式: + +```vue + + + +``` + +可用的交互模式:`grab`、`repulse`、`bubble`、`connect`、`push`、`remove`、`trail`、`attract`、`light`。 + +--- + +## 主题切换 + +通过更新响应式选项对象在运行时动态切换粒子主题: + +```vue + + + +``` + +或者,使用内置的 [themes](https://particles.js.org/docs/interfaces/Options_Interfaces_IOptions.IOptions.html#themes) 选项和容器上的 `theme` 属性进行零配置切换。 + +--- + +## 来自 @tsparticles/configs 的自定义预设 + +`@tsparticles/configs` 包导出预制的配置对象: + +```bash +npm install @tsparticles/configs +``` + +```vue + + + +``` + +浏览 `@tsparticles/configs` 包中的可用配置,获取即用型布局。 + +--- + +## 引擎初始化方式 + +有两种初始化引擎的方式: + +### 1. 全局插件(推荐) + +```typescript +// main.ts +import { createApp } from "vue"; +import App from "./App.vue"; +import type { Engine } from "@tsparticles/engine"; +import { ParticlesPlugin } from "@tsparticles/vue3"; +import { loadFull } from "tsparticles"; + +createApp(App) + .use(ParticlesPlugin, { + init: async (engine: Engine) => { + await loadFull(engine); + }, + }) + .mount("#app"); +``` + +引擎随后全局可用,所有 `` 实例共享它。 + +### 2. 组件级别初始化 + +为每个 `` 实例传递一个 `:init` 回调。当不同组件需要不同的插件集时很有用: + +```vue + +``` + +### 3. Particles Provider(组合式 API) + +使用 provider 以编程方式访问引擎: + +```vue + +``` + +--- + +## 命名导出 + TypeScript + +将所有部分组合在一起的完整 TypeScript 示例: + +```vue + + + +``` + +--- + +## API 参考 + +| 属性 | 类型 | 默认值 | 描述 | +| --------- | ----------------------------------- | --------------- | ---------------------- | +| `id` | `string` | `"tsparticles"` | 画布元素 ID | +| `options` | `ISourceOptions` | `{}` | 粒子配置 | +| `init` | `(engine: Engine) => Promise` | — | 引擎初始化回调 | +| `url` | `string` | — | 要加载 JSON 配置的 URL | + +| 事件 | 负载类型 | 描述 | +| ------------------- | ----------- | -------------------- | +| `@particles-loaded` | `Container` | 容器完全初始化时触发 | +| `@particles-init` | `Engine` | 引擎初始化后触发 | + +--- + +## 故障排除 + +- **错误:`tsparticles is not defined`** — 确保在组件渲染之前,在 `init` 回调中加载了 `tsparticles`(或所需的预设)。 +- **画布不显示** — 确认父容器有非零高度。添加 CSS 规则如 `#tsparticles { height: 100vh; }`。 +- **性能问题** — 降低 `fpsLimit`、减少 `particles.number.value`,或在低端设备上禁用 `detectRetina`。 +- **SSR(Nuxt)** — `` 组件仅限客户端。将其包裹在 `` 中或使用 `client:only` 指令。 diff --git a/websites/website/docs/zh/guides/webcomponents.md b/websites/website/docs/zh/guides/webcomponents.md new file mode 100644 index 00000000000..4fa85f8f929 --- /dev/null +++ b/websites/website/docs/zh/guides/webcomponents.md @@ -0,0 +1,359 @@ +# Web Components + +通过 `@tsparticles/webcomponents` 包将 tsParticles 与原生的 Web Components 一起使用。这种方法无需任何框架——只需要原生 JavaScript 和自定义元素。 + +## 安装 + +### 通过 CDN + +包含 tsParticles 核心和 Web Components 包: + +```html + + +``` + +### 通过 npm + 构建 + +```bash +npm install @tsparticles/webcomponents tsparticles +``` + +然后导入到你的 JavaScript 包中: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; +``` + +## 引擎初始化 + +在 `` 元素能够渲染之前,必须使用所需功能初始化引擎。使用回调调用 `initParticlesEngine`,加载所需的插件: + +```javascript +import { initParticlesEngine } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); +``` + +> **为什么需要 `loadFull`?** 它注册所有内置形状(圆形、方形、多边形、图片等)、交互(悬停、点击)和更新器(透明度、大小、颜色等)。对于更小的包,使用 `tsparticles-slim` 或按需选择单个插件。 + +## 定义自定义元素 + +引擎初始化后,注册 `` 自定义元素: + +```javascript +import { defineParticlesElement } from "@tsparticles/webcomponents"; + +defineParticlesElement(); +``` + +这将 `web-particles` 标签注册到浏览器的 `CustomElementRegistry`。可以安全地多次调用——重复注册会被忽略。 + +## 基本使用 + +`initParticlesEngine` 和 `defineParticlesElement` 都运行后,直接在 HTML 中使用该元素: + +```html + + + + + + tsParticles Web Components + + + + + + + +``` + +## 自定义配置 + +`` 元素通过 `options` 属性(JavaScript 对象)或通过 `options` 属性(JSON)接受配置。 + +### 通过 JavaScript 属性 + +```javascript +const el = document.querySelector("web-particles"); +el.options = { + background: { color: "#000000" }, + fpsLimit: 60, + particles: { + color: { value: ["#ff0000", "#00ff00", "#0000ff"] }, + links: { + enable: true, + distance: 150, + color: "#ffffff", + opacity: 0.4, + }, + move: { + enable: true, + speed: 3, + outModes: "bounce", + }, + number: { value: 60 }, + opacity: { value: 0.6 }, + shape: { type: ["circle", "square"] }, + size: { value: { min: 2, max: 6 } }, + }, + interactivity: { + events: { + onHover: { enable: true, mode: "repulse" }, + onClick: { enable: true, mode: "push" }, + }, + modes: { + repulse: { distance: 200 }, + push: { quantity: 4 }, + }, + }, +}; +``` + +### 通过 HTML 属性(JSON) + +```html + +``` + +> 使用 `options` 属性时,该值必须是有效的 JSON。对于复杂配置,推荐使用属性赋值方式。 + +## 动态创建 + +你可以完全在 JavaScript 中创建 `` 元素,并随时将其添加到 DOM: + +```javascript +import { initParticlesEngine, defineParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +defineParticlesElement(); + +function createParticles(container, config) { + const el = document.createElement("web-particles"); + el.id = "dynamic-particles"; + el.style.position = "absolute"; + el.style.width = "100%"; + el.style.height = "100%"; + el.style.top = "0"; + el.style.left = "0"; + el.options = config; + container.appendChild(el); + return el; +} + +// 使用 +const particles = createParticles(document.body, { + background: { color: "#1a1a2e" }, + particles: { + number: { value: 100 }, + links: { enable: true, color: "#e94560" }, + move: { enable: true, speed: 1 }, + }, +}); +``` + +## 扩展自定义元素 + +你可以继承 `ParticlesElement` 来创建带有内置配置的自定义元素: + +```javascript +import { initParticlesEngine, ParticlesElement } from "@tsparticles/webcomponents"; + +const { loadFull } = await import("tsparticles"); + +await initParticlesEngine(async (engine) => { + await loadFull(engine); +}); + +class MyParticlesBackground extends ParticlesElement { + constructor() { + super(); + this.style.position = "fixed"; + this.style.top = "0"; + this.style.left = "0"; + this.style.width = "100%"; + this.style.height = "100%"; + this.style.zIndex = "-1"; + } + + connectedCallback() { + this.options = { + background: { color: "#0d47a1" }, + particles: { + number: { value: 80 }, + links: { enable: true, color: "#ffffff" }, + move: { enable: true, speed: 2 }, + }, + }; + super.connectedCallback(); + } +} + +customElements.define("my-particles-bg", MyParticlesBackground); +``` + +使用: + +```html + +``` + +## 容器访问和控制 + +自定义元素暴露了 tsParticles `Container` 实例,用于命令式控制: + +```javascript +const el = document.querySelector("web-particles"); + +// 访问容器(在 connectedCallback 之后可用) +const container = el.container; +container?.pause(); +container?.play(); + +// 销毁并清理 +el.dispose(); +``` + +## 完整示例 + +一个使用 CDN 脚本的完整 HTML 页面: + +```html + + + + + + tsParticles Web Components 演示 + + + +
+

tsParticles + Web Components

+

原生自定义元素,无需框架。

+
+ + + + + + +``` + +## API 参考 + +| 导出 / 属性 | 类型 | 描述 | +| ------------------------------- | ------------------------ | ------------------------------------- | +| `initParticlesEngine(callback)` | `function` | 使用插件加载器初始化 tsParticles 引擎 | +| `defineParticlesElement()` | `function` | 注册 `` 自定义元素 | +| `ParticlesElement` | `class` | 可继承的基础类用于创建自定义元素 | +| `element.options` | `ISourceOptions` | 获取/设置粒子配置对象 | +| `element.container` | `Container \| undefined` | 底层 `Container` 的只读引用 | +| `element.dispose()` | `function` | 销毁粒子实例并清理资源 | diff --git a/websites/website/docs/zh/guides/wordpress.md b/websites/website/docs/zh/guides/wordpress.md new file mode 100644 index 00000000000..3527b1ee7b3 --- /dev/null +++ b/websites/website/docs/zh/guides/wordpress.md @@ -0,0 +1,314 @@ +--- +title: WordPress 指南 +description: 使用插件、块、短代码和主题集成将 tsParticles 与 WordPress 集成的完整指南。 +--- + +# WordPress 指南 + +## 目录 + +1. [安装](#installation) +2. [插件激活](#plugin-activation) +3. [小工具和块使用](#widget-and-block-usage) +4. [短代码使用](#shortcode-usage) +5. [PHP 过滤器配置](#php-filter-configuration) +6. [通过过滤器自定义配置](#custom-configuration-via-filter) +7. [主题集成](#theme-integration) + +--- + +## 安装 + +tsParticles WordPress 插件可通过 WordPress 插件目录获取。直接从你的 WordPress 管理后台安装。 + +### 从 WordPress 管理后台 + +1. 导航至 **插件 → 安装插件** +2. 搜索 "tsParticles" +3. 在 tsParticles 插件上点击 **立即安装** +4. 点击 **启用** + +### 手动安装 + +1. 从 WordPress 插件目录或[发布页面](https://github.com/tsparticles/wordpress/releases)下载插件 ZIP 文件 +2. 导航至 **插件 → 安装插件 → 上传插件** +3. 选择 ZIP 文件并点击 **立即安装** +4. 点击 **启用** + +--- + +## 插件激活 + +激活后,插件将注册: + +- 一个名为 "tsParticles" 的 **Gutenberg 块**,可在块插入器中使用 +- 一个 `[tsparticles]` **短代码**,用于经典编辑器或自定义 PHP 模板 +- 一个 **PHP 过滤器** `tsparticles_options`,供开发者以编程方式注入配置 +- 前端资源(JavaScript 和 CSS),仅在页面中存在块或短代码时才会入列 + +激活后,你可以通过访问 WordPress 管理侧边栏中的 **设置 → tsParticles** 来验证插件是否正常工作,根据插件版本,可能会显示一个基本设置页面。 + +--- + +## 小工具和块使用 + +tsParticles 插件为块编辑器(WordPress 5.0+)添加了一个自定义的 Gutenberg 块。 + +### 添加块 + +1. 使用块编辑器(Gutenberg)编辑任何文章或页面 +2. 点击 **+**(添加块)按钮 +3. 搜索 "tsParticles" 或 "Particles" +4. 点击 **tsParticles** 块以插入 + +### 块设置 + +插入后,块检查器面板(右侧)提供以下设置: + +- **容器 ID** — 粒子容器的唯一 HTML ID(默认:`tsparticles`) +- **宽度 / 高度** — 设置明确的尺寸或使用全屏模式 +- **Z-Index** — 控制相对于其他内容的层级 +- **配置** — 粘贴 JSON 配置对象以完全自定义粒子外观 + +对于不支持块的主题侧边栏或小工具区域,请改用[短代码](#shortcode-usage)方式。 + +--- + +## 短代码使用 + +在经典编辑器、自定义 HTML 块或直接在 PHP 模板文件中使用 `[tsparticles]` 短代码,在站点任意位置嵌入粒子背景。 + +### 基本短代码 + +``` +[tsparticles] +``` + +这将渲染默认的粒子配置(深色背景上的简单浮动圆形)。 + +### 带选项的短代码 + +使用 `options` 属性直接在短代码中传入 JSON 配置: + +``` +[tsparticles options='{"particles":{"number":{"value":50},"color":{"value":"#ff0000"},"shape":{"type":"circle"},"opacity":{"value":0.5},"size":{"value":{"min":1,"max":3}},"move":{"enable":true,"speed":1,"outModes":{"default":"bounce"}}},"background":{"color":"#1a1a2e"}}'] +``` + +### 在 PHP 模板中的短代码 + +```php +// 在你的主题的 header.php 或 footer.php 中 +echo do_shortcode('[tsparticles]'); +``` + +或者使用自定义选项: + +```php +$options = [ + 'particles' => [ + 'number' => ['value' => 80], + 'color' => ['value' => '#00d4ff'], + 'shape' => ['type' => 'circle'], + 'links' => [ + 'enable' => true, + 'distance' => 150, + 'color' => '#00d4ff', + 'opacity' => 0.3, + ], + 'move' => [ + 'enable' => true, + 'speed' => 1.5, + 'outModes' => ['default' => 'bounce'], + ], + ], + 'background' => ['color' => '#0d1117'], +]; + +echo do_shortcode('[tsparticles options=\'' . wp_json_encode($options) . '\']'); +``` + +--- + +## PHP 过滤器配置 + +插件暴露了一个 `tsparticles_options` 过滤器,让你可以从主题的 `functions.php` 文件或自定义插件中覆盖或扩展粒子配置。这是推荐给开发者的方式,因为它将配置保留在 PHP 中,避免了内联 JSON。 + +### 基本过滤器 + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + $options['background'] = ['color' => '#0d1117']; + $options['particles']['number']['value'] = 100; + $options['particles']['color']['value'] = '#00d4ff'; + $options['particles']['shape']['type'] = 'circle'; + $options['particles']['opacity']['value'] = 0.6; + $options['particles']['size']['value'] = ['min' => 2, 'max' => 5]; + $options['particles']['links']['enable'] = true; + $options['particles']['links']['distance'] = 150; + $options['particles']['links']['color'] = '#00d4ff'; + $options['particles']['links']['opacity'] = 0.3; + $options['particles']['move']['enable'] = true; + $options['particles']['move']['speed'] = 1.5; + $options['particles']['move']['outModes']['default'] = 'bounce'; + return $options; +}); +``` + +此过滤器在短代码或块渲染之前运行,因此页面上任何 tsParticles 实例都会收到自定义配置。 + +--- + +## 通过过滤器自定义配置 + +以下是一个完整的自定义配置,展示了过滤器的全部功能——包括交互功能、多种形状类型和主题支持。 + +```php +// functions.php +add_filter('tsparticles_options', function (array $options): array { + + // 全屏背景 + $options['fullScreen'] = [ + 'enable' => true, + 'zIndex' => -1, + ]; + + $options['fpsLimit'] = 60; + + // 粒子设置 + $options['particles'] = [ + 'number' => [ + 'value' => 60, + 'density' => ['enable' => true, 'width' => 800, 'height' => 800], + ], + 'color' => [ + 'value' => ['#ff6b6b', '#feca57', '#48dbfb', '#ff9ff3', '#54a0ff'], + ], + 'shape' => [ + 'type' => ['circle', 'triangle', 'polygon'], + 'options' => [ + 'polygon' => ['sides' => 6], + ], + ], + 'opacity' => [ + 'value' => ['min' => 0.4, 'max' => 0.8], + ], + 'size' => [ + 'value' => ['min' => 3, 'max' => 8], + ], + 'links' => [ + 'enable' => true, + 'distance' => 200, + 'color' => '#ffffff', + 'opacity' => 0.15, + 'width' => 1, + ], + 'move' => [ + 'enable' => true, + 'speed' => 2, + 'direction' => 'none', + 'random' => true, + 'straight' => false, + 'outModes' => ['default' => 'out'], + ], + ]; + + // 交互 + $options['interactivity'] = [ + 'events' => [ + 'onHover' => ['enable' => true, 'mode' => 'attract'], + 'onClick' => ['enable' => true, 'mode' => 'repulse'], + ], + 'modes' => [ + 'attract' => ['distance' => 200, 'duration' => 0.4, 'factor' => 1], + 'repulse' => ['distance' => 200, 'duration' => 0.4], + ], + ]; + + // 背景 + $options['background'] = [ + 'color' => '#0f0f23', + ]; + + // 主题支持——浅色模式切换 + $options['themes'] = [ + [ + 'name' => 'light', + 'default' => ['value' => false], + 'options' => [ + 'background' => ['color' => '#f0f0f5'], + 'particles' => [ + 'color' => ['value' => ['#e74c3c', '#2ecc71', '#3498db', '#f1c40f']], + 'links' => ['color' => '#333333', 'opacity' => 0.2], + ], + ], + ], + ]; + + return $options; +}); +``` + +--- + +## 主题集成 + +要将 tsParticles 作为整个 WordPress 主题的持久背景,将短代码或直接 PHP 调用添加到主题的 `header.php` 或 `footer.php`。 + +### 页眉背景 + +```php + + +
+ +
+ +``` + +### 全屏背景样式 + +将以下 CSS 添加到主题的 `style.css` 或通过 `wp_add_inline_style` 添加: + +```css +#tsparticles-background { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + z-index: -1; + pointer-events: none; +} + +/* 确保内容出现在粒子之上 */ +.site-content { + position: relative; + z-index: 1; +} +``` + +### 有条件的加载 + +要仅在特定页面上加载 tsParticles: + +```php +// 在 functions.php 中——仅在前台页面入列 +add_action('wp', function () { + if (is_front_page()) { + add_filter('tsparticles_options', function (array $options): array { + $options['particles']['number']['value'] = 120; + $options['particles']['color']['value'] = '#ffffff'; + $options['particles']['move']['speed'] = 0.8; + $options['background']['color'] = '#1a1a2e'; + return $options; + }); + } +}); +``` + +将其与块或短代码放置结合使用,可创建高性能、页面特定的粒子背景。 + +--- + +你现在已拥有将 tsParticles 集成到 WordPress 站点所需的全部内容。无论你偏好块编辑器、短代码还是完整的 PHP 控制,每种方式都能以最小的努力为你带来独特的粒子背景。 diff --git a/websites/website/package.json b/websites/website/package.json index c224bb25d79..0f351bd58bd 100644 --- a/websites/website/package.json +++ b/websites/website/package.json @@ -10,8 +10,8 @@ "docs:typedoc": "node ./scripts/sync-typedoc.mjs", "docs:assets": "node ./scripts/sync-public-assets.mjs", "dev": "pnpm run typedoc:api && pnpm run docs:typedoc && pnpm run docs:assets && vitepress dev docs --host", - "docs:build": "pnpm run typedoc:api && pnpm run docs:typedoc && pnpm run lint:fix && pnpm run docs:assets && vitepress build docs && node ./scripts/merge-sitemaps.mjs", - "docs:build:ci": "pnpm run typedoc:api && pnpm run docs:typedoc && pnpm run lint && pnpm run docs:assets && vitepress build docs && node ./scripts/merge-sitemaps.mjs", + "docs:build": "pnpm run typedoc:api && pnpm run docs:typedoc && pnpm run lint:fix && pnpm run docs:assets && NODE_OPTIONS=--max-old-space-size=4096 vitepress build docs && node ./scripts/merge-sitemaps.mjs", + "docs:build:ci": "pnpm run typedoc:api && pnpm run docs:typedoc && pnpm run lint && pnpm run docs:assets && NODE_OPTIONS=--max-old-space-size=4096 vitepress build docs && node ./scripts/merge-sitemaps.mjs", "docs:preview": "vitepress preview docs --host", "build": "pnpm run docs:build", "lint": "prettier --check \"docs/**/*.{md,ts,css}\"",