GithubHelp home page GithubHelp logo

tsparticles / react Goto Github PK

View Code? Open in Web Editor NEW
311.0 4.0 24.0 1.39 MB

React tsParticles official component

Home Page: https://particles.js.org

License: MIT License

Shell 0.15% CSS 24.78% TypeScript 31.54% JavaScript 33.70% HTML 9.83%
2d animations canvas confetti fireworks hacktoberfest javascript js npm particles

react's Introduction

banner

@tsparticles/react

npm npm GitHub Sponsors

Official tsParticles ReactJS component

Slack Discord Telegram

tsParticles Product Hunt

Installation

npm install @tsparticles/react

or

yarn add @tsparticles/react

TypeScript Installation

npm install @tsparticles/react @tsparticles/engine

or

yarn add @tsparticles/react @tsparticles/engine

@tsparticles/engine is the core package for tsParticles, it contains useful types like ISourceOptions, Engine or Container.

create-react-app

Starting from version 1.17.0 there are two official create-react-app templates:

  • cra-template-particles: Simple ReactJS template with full screen particles, using JavaScript
  • cra-template-particles-typescript: Simple ReactJS template with full screen particles, using TypeScript

You can simply install them using the create-react-app command like this:

$ create-react-app your_app --template particles

or

$ create-react-app your_app --template particles-typescript

How to use

Code

Examples:

Options object

JavaScript support - object
import { useEffect, useMemo, useState } from "react";
import Particles, { initParticlesEngine } from "@tsparticles/react";
// import { loadAll } from "@tsparticles/all"; // if you are going to use `loadAll`, install the "@tsparticles/all" package too.
// import { loadFull } from "tsparticles"; // if you are going to use `loadFull`, install the "tsparticles" package too.
import { loadSlim } from "@tsparticles/slim"; // if you are going to use `loadSlim`, install the "@tsparticles/slim" package too.
// import { loadBasic } from "@tsparticles/basic"; // if you are going to use `loadBasic`, install the "@tsparticles/basic" package too.

const App = () => {
  const [init, setInit] = useState(false);

  // this should be run only once per application lifetime
  useEffect(() => {
    initParticlesEngine(async (engine) => {
      // you can initiate the tsParticles instance (engine) here, adding custom shapes or presets
      // this loads the tsparticles package bundle, it's the easiest method for getting everything ready
      // starting from v2 you can add only the features you need reducing the bundle size
      //await loadAll(engine);
      //await loadFull(engine);
      await loadSlim(engine);
      //await loadBasic(engine);
    }).then(() => {
      setInit(true);
    });
  }, []);

  const particlesLoaded = (container) => {
    console.log(container);
  };

  const options = useMemo(
    () => ({
      background: {
        color: {
          value: "#0d47a1",
        },
      },
      fpsLimit: 120,
      interactivity: {
        events: {
          onClick: {
            enable: true,
            mode: "push",
          },
          onHover: {
            enable: true,
            mode: "repulse",
          },
        },
        modes: {
          push: {
            quantity: 4,
          },
          repulse: {
            distance: 200,
            duration: 0.4,
          },
        },
      },
      particles: {
        color: {
          value: "#ffffff",
        },
        links: {
          color: "#ffffff",
          distance: 150,
          enable: true,
          opacity: 0.5,
          width: 1,
        },
        move: {
          direction: "none",
          enable: true,
          outModes: {
            default: "bounce",
          },
          random: false,
          speed: 6,
          straight: false,
        },
        number: {
          density: {
            enable: true,
          },
          value: 80,
        },
        opacity: {
          value: 0.5,
        },
        shape: {
          type: "circle",
        },
        size: {
          value: { min: 1, max: 5 },
        },
      },
      detectRetina: true,
    }),
    [],
  );

  if (init) {
    return (
      <Particles
        id="tsparticles"
        particlesLoaded={particlesLoaded}
        options={options}
      />
    );
  }

  return <></>;
};
TypeScript support - object
import { useEffect, useMemo, useState } from "react";
import Particles, { initParticlesEngine } from "@tsparticles/react";
import {
  type Container,
  type ISourceOptions,
  MoveDirection,
  OutMode,
} from "@tsparticles/engine";
// import { loadAll } from "@tsparticles/all"; // if you are going to use `loadAll`, install the "@tsparticles/all" package too.
// import { loadFull } from "tsparticles"; // if you are going to use `loadFull`, install the "tsparticles" package too.
import { loadSlim } from "@tsparticles/slim"; // if you are going to use `loadSlim`, install the "@tsparticles/slim" package too.
// import { loadBasic } from "@tsparticles/basic"; // if you are going to use `loadBasic`, install the "@tsparticles/basic" package too.

const App = () => {
  const [init, setInit] = useState(false);

  // this should be run only once per application lifetime
  useEffect(() => {
    initParticlesEngine(async (engine) => {
      // you can initiate the tsParticles instance (engine) here, adding custom shapes or presets
      // this loads the tsparticles package bundle, it's the easiest method for getting everything ready
      // starting from v2 you can add only the features you need reducing the bundle size
      //await loadAll(engine);
      //await loadFull(engine);
      await loadSlim(engine);
      //await loadBasic(engine);
    }).then(() => {
      setInit(true);
    });
  }, []);

  const particlesLoaded = async (container?: Container): Promise<void> => {
    console.log(container);
  };

  const options: ISourceOptions = useMemo(
    () => ({
      background: {
        color: {
          value: "#0d47a1",
        },
      },
      fpsLimit: 120,
      interactivity: {
        events: {
          onClick: {
            enable: true,
            mode: "push",
          },
          onHover: {
            enable: true,
            mode: "repulse",
          },
        },
        modes: {
          push: {
            quantity: 4,
          },
          repulse: {
            distance: 200,
            duration: 0.4,
          },
        },
      },
      particles: {
        color: {
          value: "#ffffff",
        },
        links: {
          color: "#ffffff",
          distance: 150,
          enable: true,
          opacity: 0.5,
          width: 1,
        },
        move: {
          direction: MoveDirection.none,
          enable: true,
          outModes: {
            default: OutMode.out,
          },
          random: false,
          speed: 6,
          straight: false,
        },
        number: {
          density: {
            enable: true,
          },
          value: 80,
        },
        opacity: {
          value: 0.5,
        },
        shape: {
          type: "circle",
        },
        size: {
          value: { min: 1, max: 5 },
        },
      },
      detectRetina: true,
    }),
    [],
  );

  if (init) {
    return (
      <Particles
        id="tsparticles"
        particlesLoaded={particlesLoaded}
        options={options}
      />
    );
  }

  return <></>;
};

Remote url

JavaScript support - url
import { useEffect, useState } from "react";
import Particles, { initParticlesEngine } from "@tsparticles/react";
// import { loadAll } from "@tsparticles/all"; // if you are going to use `loadAll`, install the "@tsparticles/all" package too.
// import { loadFull } from "tsparticles"; // if you are going to use `loadFull`, install the "tsparticles" package too.
import { loadSlim } from "@tsparticles/slim"; // if you are going to use `loadSlim`, install the "@tsparticles/slim" package too.
// import { loadBasic } from "@tsparticles/basic"; // if you are going to use `loadBasic`, install the "@tsparticles/basic" package too.

const App = () => {
  const [init, setInit] = useState(false);

  // this should be run only once per application lifetime
  useEffect(() => {
    initParticlesEngine(async (engine) => {
      // you can initiate the tsParticles instance (engine) here, adding custom shapes or presets
      // this loads the tsparticles package bundle, it's the easiest method for getting everything ready
      // starting from v2 you can add only the features you need reducing the bundle size
      //await loadAll(engine);
      //await loadFull(engine);
      await loadSlim(engine);
      //await loadBasic(engine);
    }).then(() => {
      setInit(true);
    });
  }, []);

  const particlesLoaded = (container) => {
    console.log(container);
  };

  if (init) {
    return (
      <Particles
        id="tsparticles"
        url="http://foo.bar/particles.json"
        particlesLoaded={particlesLoaded}
      />
    );
  }

  return <></>;
};
TypeScript support - url
import { useEffect, useState } from "react";
import Particles, { initParticlesEngine } from "@tsparticles/react";
import type { Container } from "@tsparticles/engine";
// import { loadAll } from "@tsparticles/all"; // if you are going to use `loadAll`, install the "@tsparticles/all" package too.
// import { loadFull } from "tsparticles"; // if you are going to use `loadFull`, install the "tsparticles" package too.
import { loadSlim } from "@tsparticles/slim"; // if you are going to use `loadSlim`, install the "@tsparticles/slim" package too.
// import { loadBasic } from "@tsparticles/basic"; // if you are going to use `loadBasic`, install the "@tsparticles/basic" package too.

const App = () => {
  const [init, setInit] = useState(false);

  // this should be run only once per application lifetime
  useEffect(() => {
    initParticlesEngine(async (engine) => {
      // you can initiate the tsParticles instance (engine) here, adding custom shapes or presets
      // this loads the tsparticles package bundle, it's the easiest method for getting everything ready
      // starting from v2 you can add only the features you need reducing the bundle size
      //await loadAll(engine);
      //await loadFull(engine);
      await loadSlim(engine);
      //await loadBasic(engine);
    }).then(() => {
      setInit(true);
    });
  }, []);

  const particlesLoaded = (container?: Container) => {
    console.log(container);
  };

  if (init) {
    return (
      <Particles
        id="tsparticles"
        url="http://foo.bar/particles.json"
        particlesLoaded={particlesLoaded}
      />
    );
  }

  return <></>;
};

Props

Prop Type Definition
id string The id of the element.
width string The width of the canvas.
height string The height of the canvas.
options object The options of the particles instance.
url string The remote options url, called using an AJAX request
style object The style of the canvas element.
className string The class name of the canvas wrapper.

particles.json

Find all configuration options here.

You can find sample configurations here 📖

Demos

Preset demos can be found here

There's also a CodePen collection actively maintained and updated here

Report bugs and issues here

tsParticle Website

react's People

Contributors

ivanjeremic avatar matteobruni avatar okhomenko avatar renovate[bot] avatar simonpaul02 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react's Issues

Please fix TypeScript support - object

TypeScript support - object
import { useEffect, useMemo, useState } from "react";
import Particles, { initParticlesEngine } from "@tsparticles/react";
import {
  type Container,
  type ISourceOptions,
  MoveDirection,
  OutMode,
} from "@tsparticles/engine";
// import { loadAll } from "@/tsparticles/all"; // if you are going to use `loadAll`, install the "@tsparticles/all" package too.
// import { loadFull } from "tsparticles"; // if you are going to use `loadFull`, install the "tsparticles" package too.
import { loadSlim } from "@tsparticles/slim"; // if you are going to use `loadSlim`, install the "@tsparticles/slim" package too.
// import { loadBasic } from "@tsparticles/basic"; // if you are going to use `loadBasic`, install the "@tsparticles/basic" package too.

const App = () => {
  const [init, setInit] = useState(false);

  // this should be run only once per application lifetime
  useEffect(() => {
    initParticlesEngine(async (engine) => {
      // you can initiate the tsParticles instance (engine) here, adding custom shapes or presets
      // this loads the tsparticles package bundle, it's the easiest method for getting everything ready
      // starting from v2 you can add only the features you need reducing the bundle size
      //await loadAll(engine);
      //await loadFull(engine);
      await loadSlim(engine);
      //await loadBasic(engine);
    }).then(() => {
      setInit(true);
    });
  }, []);

  const particlesLoaded = async (container?: Container): Promise<void> => {
    console.log(container);
  };

  const options: ISourceOptions = useMemo(
    () => ({
      background: {
        color: {
          value: "#0d47a1",
        },
      },
      fpsLimit: 120,
      interactivity: {
        events: {
          onClick: {
            enable: true,
            mode: "push",
          },
          onHover: {
            enable: true,
            mode: "repulse",
          },
        },
        modes: {
          push: {
            quantity: 4,
          },
          repulse: {
            distance: 200,
            duration: 0.4,
          },
        },
      },
      particles: {
        color: {
          value: "#ffffff",
        },
        links: {
          color: "#ffffff",
          distance: 150,
          enable: true,
          opacity: 0.5,
          width: 1,
        },
        move: {
          direction: MoveDirection.none,
          enable: true,
          outModes: {
            default: OutMode.out,
          },
          random: false,
          speed: 6,
          straight: false,
        },
        number: {
          density: {
            enable: true,
          },
          value: 80,
        },
        opacity: {
          value: 0.5,
        },
        shape: {
          type: "circle",
        },
        size: {
          value: { min: 1, max: 5 },
        },
      },
      detectRetina: true,
    }),
    [],
  );

  if (init) {
    return (
      <Particles
        id="tsparticles"
        particlesLoaded={particlesLoaded}
        options={options}
      />
    );
  }

  return <></>;
};

Errors:

Line-36 options : It looks like there is a type error in your TypeScript code. The issue is with the particles.move.direction property in the options object. The error message indicates that the type of particles.move.direction is incompatible with the expected type. You may need to check the type definition for direction and ensure that it matches the expected type for ISourceOptions.

Line-77 MoveDirection : The issue const enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query occurs when you try to directly use a const enum in a place where it's not allowed in TypeScript. In your case, the error is happening because you're trying to use the MoveDirection enum directly in the move object without referencing a specific property or index.

Line-80 OutMode : The error const enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query is likely occurring because you are trying to use the OutMode const enum in a context where it is not allowed.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • fix(deps): update dependency @tsparticles/configs to v3.3.0
  • fix(deps): update dependency @tsparticles/engine to v3.3.0
  • fix(deps): update dependency @types/node to v20.12.7
  • fix(deps): update dependency lerna to v8.1.2
  • fix(deps): update dependency prettier to v3.2.5
  • fix(deps): update dependency tsparticles to v3.3.0
  • fix(deps): update dependency typescript to v5.4.5
  • fix(deps): update nextjs monorepo to v14.2.2 (@next/font, eslint-config-next, next)
  • fix(deps): update testing-library monorepo (@testing-library/jest-dom, @testing-library/react, @testing-library/user-event)
  • chore(deps): update dependency eslint to v9
  • fix(deps): update commitlint monorepo to v19 (major) (@commitlint/cli, @commitlint/config-conventional)
  • fix(deps): update dependency @testing-library/react to v15
  • 🔐 Create all rate-limited PRs at once 🔐

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/nodejs.yml
  • actions/checkout v4
  • actions/setup-node v4
  • pnpm/action-setup v3.0.0
  • actions/cache v4
  • actions/checkout v4
  • actions/setup-node v4
  • pnpm/action-setup v3.0.0
  • actions/cache v4
npm
apps/nextjs-beta/package.json
  • @next/font ^14.0.3
  • @tsparticles/configs ^3.0.2
  • @tsparticles/engine ^3.0.2
  • @types/node ^20.10.4
  • @types/react ^18.2.42
  • @types/react-dom ^18.2.17
  • eslint ^8.55.0
  • eslint-config-next ^14.0.3
  • next ^14.0.3
  • react ^18.2.0
  • react-dom ^18.2.0
  • tsparticles ^3.0.2
  • typescript ^5.3.3
apps/nextjs/package.json
  • @tsparticles/engine ^3.0.2
  • @tsparticles/preset-big-circles ^3.0.0
  • next ^14.0.3
  • react ^18.2.0
  • react-dom ^18.2.0
  • typescript ^5.3.3
  • eslint ^8.55.0
  • eslint-config-next ^14.0.3
apps/react/package.json
  • @tsparticles/engine ^3.0.2
  • react ^18.2.0
  • react-dom ^18.2.0
  • react-scripts ^5.0.1
  • tsparticles ^3.0.2
  • web-vitals ^3.5.0
components/react/package.json
  • @tsparticles/engine ^3.0.2
  • @types/react ^18.2.45
  • @types/react-dom ^18.2.18
  • @typescript-eslint/eslint-plugin ^7.0.0
  • @typescript-eslint/parser ^7.0.0
  • @vitejs/plugin-react ^4.2.1
  • eslint ^8.56.0
  • eslint-plugin-react-hooks ^4.6.0
  • eslint-plugin-react-refresh ^0.4.5
  • glob ^10.3.10
  • react ^18.2.0
  • react-dom ^18.2.0
  • typescript ^5.3.3
  • vite ^5.0.10
  • vite-plugin-dts ^3.6.4
  • vite-plugin-lib-inject-css ^1.3.0
  • @tsparticles/engine ^3.0.2
  • react >=16.8.0
  • react-dom >=16.8.0
package.json
  • @commitlint/cli ^18.4.3
  • @commitlint/config-conventional ^18.4.3
  • husky ^9.0.0
  • lerna ^8.0.1
  • prettier ^3.1.1
  • process ^0.11.10
  • react-error-overlay ^6.0.11
templates/react-ts/package.json
  • @testing-library/jest-dom ^6.1.5
  • @testing-library/react ^14.1.2
  • @testing-library/user-event ^14.5.1
  • @tsparticles/engine ^3.0.2
  • @types/jest ^29.5.10
  • @types/node ^20.10.3
  • @types/react ^18.2.42
  • @types/react-dom ^18.2.17
  • tslib ^2.6.2
  • tsparticles ^3.0.2
  • typescript ^5.3.3
  • web-vitals ^3.5.0
  • fs-extra ^11.2.0
templates/react/package.json
  • @tsparticles/engine ^3.0.2
  • tslib ^2.6.2
  • tsparticles ^3.0.2
  • fs-extra ^11.2.0

  • Check this box to trigger a request for Renovate to run again on this repository

Particles started loading very slowly recently

Hi there! Thanks for all the work you've put into this library. I've recently noticed that the particles, which would've taken no more than 500ms to load before, suddenly started taking very long to load on my website.

Screen record:

Screen.Recording.2024-03-01.at.8.47.39.pm.mov

Site: https://www.maxwowo.com/

Repo: https://github.com/maxwowo/maxwowo

File that mounts the particles: https://github.com/maxwowo/maxwowo/blob/master/src/components/particles.tsx

This is the case across Chrome, Firefox, and Safari. My site should be pretty simple in structure and I also haven't made any changes to it recently, so just wondering what might be going on

Cheers

Particles not showing.

I'm trying to implement this https://codepen.io/idofugh/pen/KKrXJGE into a React website but I cannot seem to make it work.

First I've tried to create a TsParticles.jsx component like so:

import React, { useEffect } from 'react';
import Particles from 'react-tsparticles';
import noise from 'noisejs';


const TsParticles = () => {
  let noiseZ;
  let size;
  let columns;
  let rows;
  let w;
  let h;
  let field;

  const options = {
    background: {
      color: {
        value: '#161616',
      },
    },
    fpsLimit: 120,
    particles: {
      number: {
        value: 0,
      },
    },
    detectRetina: true,
    pauseOnBlur: true,
  };

  useEffect(() => {
    const setup = (container, options) => {
      size = 20;
      noiseZ = 0;
      reset(container);
      window.addEventListener('resize', reset);
    };

    const initField = () => {
      field = new Array(columns);
      for (let x = 0; x < columns; x++) {
        field[x] = new Array(columns);
        for (let y = 0; y < rows; y++) {
          field[x][y] = [0, 0];
        }
      }
    };

    const calculateField = () => {
      for (let x = 0; x < columns; x++) {
        for (let y = 0; y < rows; y++) {
          let angle = noise.perlin3(x / 50, y / 50, noiseZ) * Math.PI * 2;
          let length = noise.perlin3(x / 100 + 40000, y / 100 + 40000, noiseZ);
          field[x][y][0] = angle;
          field[x][y][1] = length;
        }
      }
    };

    const reset = (container) => {
      w = container.canvas.size.width;
      h = container.canvas.size.height;
      noise.seed(Math.random());
      columns = Math.floor(w / size) + 1;
      rows = Math.floor(h / size) + 1;
      initField();
    };

    const drawField = (ctx) => {
      for (let x = 0; x < columns; x++) {
        for (let y = 0; y < rows; y++) {
          let angle = field[x][y][0];
          let length = field[x][y][1];
          ctx.save();
          ctx.translate(x * size, y * size);
          ctx.rotate(angle);
          ctx.strokeStyle = 'white';
          ctx.beginPath();
          ctx.moveTo(0, 0);
          ctx.lineTo(0, size * length);
          ctx.stroke();
          ctx.restore();
        }
      }
    };

    return () => {
      window.removeEventListener('resize', reset);
    };
  }, []);

  const handleInit = (particles) => {
    // You can leave this empty since the setup logic is already defined in the useEffect hook
  };

  const handleLoaded = (particles) => {
    // You can leave this empty since the loaded logic is already defined in the useEffect hook
  };

  return (
    <Particles
      id="tsparticles"
      init={(particles) => handleInit(particles, options)}
      loaded={(particles) => handleLoaded(particles, options)}
      options={options}
    />
  );
};

export default TsParticles;

but I had no luck making it work, so I though I'll just pop it in a JS file and import the file inside the app.js. Managed to get rid of all the errors and I've ended up with this:

import { tsParticles } from "tsparticles-engine";
import noise from "noisejs";

let noiseZ;
let size;
let columns;
let rows;
let w;
let h;
let field;

let container;
const noiseInstance = new noise.Noise();

function setup(container) {
  size = 20;
  noiseZ = 0;
  reset(container);
  window.addEventListener("resize", reset);
}

function initField() {
  field = new Array(columns);
  for (let x = 0; x < columns; x++) {
    field[x] = new Array(columns);
    for (let y = 0; y < rows; y++) {
      field[x][y] = [0, 0];
    }
  }
}

function calculateField() {
  for (let x = 0; x < columns; x++) {
    for (let y = 0; y < rows; y++) {
      let angle = noiseInstance.simplex2(x / 50, y / 50) * Math.PI * 2;
      let length = noiseInstance.simplex2(x / 100 + 40000, y / 100 + 40000);
      field[x][y][0] = angle;
      field[x][y][1] = length;
    }
  }
}

function reset(container) {
  w = container.canvas.size.width;
  h = container.canvas.size.height;
  noiseInstance.seed(Math.random());
  columns = Math.floor(w / size) + 1;
  rows = Math.floor(h / size) + 1;
  initField();
}

function drawField(ctx) {
  for (let x = 0; x < columns; x++) {
    for (let y = 0; y < rows; y++) {
      let angle = field[x][y][0];
      let length = field[x][y][1];
      ctx.save();
      ctx.translate(x * size, y * size);
      ctx.rotate(angle);
      ctx.strokeStyle = "lightgrey"; // color.
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.lineTo(0, size * length);
      ctx.stroke();
      ctx.restore();
    }
  }
}

tsParticles
  .load("tsparticles", {
    background: {
      color: {
        value: "#161616"
      }
    },
    fpsLimit: 120,
    particles: {
      number: {
        value: 0
      }
    },
    detectRetina: true,
    pauseOnBlur: true
  })
  .then((container) => {
    container.setNoise({
      init: function () {
        setup(container);
      },
      update: function () {
        calculateField();

        const mousePos = container.interactivity.mouse.position;

        let sumZ;

        if (mousePos) {
          sumZ =
            (mousePos.x * mousePos.y) /
            (25 * container.canvas.size.width * container.canvas.size.height);
        } else {
          sumZ = 0.004;
        }

        noiseZ += sumZ;

        drawField(container.canvas.context);
      }
    });

    container.refresh();
  });

The problem is, there are no particles visible. The

gets displayed but there are no particles.

I apologise if this is not the place to ask this question.

`console.dir` is left in code

Issue

I noticed that the library is logging information about Particles component to the browser console
image

This is the line that causes the console logging (in node_modules/react-particles/particles.js)
image

These are the packages that I installed:

"react-particles": "^2.10.1",
"tsparticles": "^2.10.1",

I used the example code from here: https://github.com/tsparticles/react#typescript-support---object

Attempt to fix

I tried to uninstall and reinstall the package:

 npm uninstall react-particles
 npm install react-particles

but that line of code still remains in the downloaded code in node_modules.

Vector.js error

I'm having an error at @tsparticles/engine/browser/Core/Utils/Vector.js
Uncaught TypeError: Class extends value undefined is not a constructor or null

tsCapture

Any resolution for this?

Update license to MIT same as @tsparticles/engine

Can we update license to MIT?

How to reproduce

npm i -S --save-exact  @tsparticles/[email protected]
npx license-checker --unknown --packages @tsparticles/[email protected]

Output

└─ @tsparticles/react
   ├─ licenses: UNKNOWN
   ├─ dependencyPath: /Users/okhomenko/test/node_modules/@tsparticles/react
   ├─ path: /Users/okhomenko/test/node_modules/@tsparticles/react
   └─ licenseFile: /Users/okhomenko/test/node_modules/@tsparticles/react/LICENSE

I guess it happens because license property is not explicit in the packages.json.

For example @tsparticles/engine has MIT in package.json

  "license": "MIT",

After these changes it seems not working with autoPlay: false

@Kritika30032002

Looks like something important was removed with that bunch of deleted code. When I use the new function version of the Particles component I end up with the destroyed variable as 'true' even before calling play().
Duration isn't set in options and by call stack, it happens some safelyCallDestroy() where it calls destroy() itself

With those concerns, I've decided to try the original class version and it works perfectly fine without changing any of my code
I also created 2 branches in case of need to reproduce the problem. Please, see https://github.com/Squikle/MemIt/branches
-npm run dev
-go to http://localhost:5173/terms/1
-press the green button to finish a stack
-see particles don't start with the new function component version and some logs of the destroyed variable show it's 'true'

Sorry I don't have much time for deep investigation or fork but contact me if you need some additional information

Fast route changes causes component render outside #root

Having an issue, using latest Vite and TSParticles. When I change routes too fast TSParticles renders outside the root. I am using particles inside a component to place it in specific divs, already using the fullscreen option and works fine until fast route changes.

I have tried creating a destroy method but it doesn't seem to be working. Here is a lightweight reproduction. Try change routes fast and you will notice it extends the height of the document.

https://codesandbox.io/p/sandbox/vigorous-austin-f34z57

Changing theme crashes page

Looks like the issue mentioned in this ticket: #21 is still an issue in the current release 2.11.0.
When I change the theme by either explicitly calling loadTheme OR switching the browser's prefers-color-scheme with auto: true enabled in the theme, the whole page freezes.

The react demo app included in this repo also freezes when clicking one of the theme buttons.

Here is my code in case it helps at all. And I am running this on Windows 11 in both Chrome and Firefox with the issue.

import type { ISourceOptions } from "tsparticles-engine";
import { useCallback, useEffect, useRef } from "react";
import type { Container, Engine } from "tsparticles-engine";
import ReactParticles from "react-tsparticles";
import { loadSlim } from "tsparticles-slim";
import { useTheme } from "~/utils/theme-provider";

const options: ISourceOptions = {
  name: "Link Triangles",
  themes: [
    {
      name: "light",
      default: {
        auto: true,
        value: true,
        mode: "light",
      },
      options: {
        background: {
          color: "#ffffff",
        },
        particles: {
          color: {
            value: "#5b21b6",
          },
          links: {
            color: {
              value: "#a78bfa",
            },
            triangles: {
              color: "#6d28d9",
            },
          },
        },
      },
    },
    {
      name: "dark",
      default: {
        auto: true,
        value: true,
        mode: "dark",
      },
      options: {
        background: {
          color: "#000000",
        },
        particles: {
          color: {
            value: "#8b5cf6",
          },
          links: {
            color: {
              value: "#a78bfa",
            },
            triangles: {
              color: "#a78bfa",
            },
          },
        },
      },
    },
  ],
  particles: {
    ...
  },
};

const Particles = () => {
  const [theme] = useTheme(); // This returns "light" or "dark"

  const containerRef = useRef<Container>();

  const particlesInit = useCallback(async (engine: Engine) => {
    await loadSlim(engine);
  }, []);

  const particlesLoaded = useCallback(
    async (container: Container | undefined) => {
      containerRef.current = container;
    },
    []
  );

  useEffect(() => {
    if (!containerRef.current) return;
    containerRef.current?.loadTheme(theme!);
  }, [theme]);

  return (
    <ReactParticles
      id="tsparticles"
      init={particlesInit}
      loaded={particlesLoaded}
      options={options}
    />
  );
};

tsparticles causing build to fail

I just wanted to let you know, that I had issues with building my Astro website after I added tsparticles to it.

The following is the stack trace of the failed build I get:

node:internal/process/promises:289
            triggerUncaughtException(err, true /* fromPromise */);
            ^

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Changing the Particles component import from a default, to a regular import did the job (import { Particles } from 'react-particles' instead of import Particles from 'react-particles').

I don't know if this is just an Astro issue, or why your documentation advises one to import Particles as a default import, just wanted to inform you of this issue and it's fix 😃
Cheers!

Particles on one component, staying even when I scroll to another component

Contact Details

[email protected]

What do you need?

Hello !

This is my first post and I'm a very beginner programmer, so sorry in advance if anything missing.

I am on React with Next.js.

I would like to create a website with particles on my Homepage, which correspond to a component named "Home".
And the particles should disappear on the component below named "Technologies".
Basically, I would like to get something similar to that regarding the particles : https://whosbl33h.netlify.app/

The problem on my side is that particles stay even when I scroll down.

Here are my codes below.

Component Home.js :

import styles from '../styles/Home.module.css';
import Particles from 'react-tsparticles';
import { useCallback } from "react";
import { loadSlim } from "tsparticles-slim";
import { particlesOptions } from './Particles/particlesOptions';

function Home() {

  let isInitialized = false;

  const particlesInit = useCallback(async (engine) => {
    if(!isInitialized) {
      await loadSlim(engine);
      isInitialized = true;
    }
  }, []);

  const particlesLoaded = useCallback(async (container) => {
    await container
  }, []);

  return (
    <div>
      <Particles
      id="tsparticles"
      init={particlesInit}
      loaded={particlesLoaded}
      options={particlesOptions}
      />
      <main className={styles.main}>
        <h1 className={styles.title}>
          Welcome to <a href="https://nextjs.org">Next.js!</a>
        </h1>
      </main>
    </div>
  );
}

export default Home;

ParticlesOptions :

export const particlesOptions = {

  interactivity: {
      detect_on: "canvas",
      
      autoPlay: true,

      fullScreen: {
        enable: false,
        zIndex: 0,
      },

      events: {
          onClick: {
              enable: true,
              mode: "repulse",
          },
          onHover: {
              enable: true, 
              mode: "bubble", 
              parallax: {
                enable: true, 
                force: 100, 
                smooth: 60, 
              },
          },
          resize: {
            delay: 0.5,
            enable: true,
          },
      },

      modes: {
          push: {
              quantity: 4,
          },
          repulse: {
              distance: 300,
              duration: 1.5,
          },
          bubble: {
              distance: 100,
              duration: 0.4,
              size: 40,
              color: {
                value: '#EAB441',
              },
              opacity: 8,
              mix: false,
          },
      },
  },

  particles: {
      collisions: {
        enable: true,
        mode: 'bounce',
      },
      color: {
          value: '#fff',
      },
      links: {
          color: "#808080",
          distance: 150,
          enable: true,
          opacity: 0.5,
          width: 1,
      },
      move: {
          direction: "none",
          enable: true,
          outModes: {
              default: "bounce",
          },
          random: true,
          speed: 0.5,
          straight: false,
      },
      number: {
          density: {
              enable: false,
          },
          value: 27,
      },
      opacity: {
          value: 0.3,
      },
      shape: {
          type: 'char',
          character: [
            {
              font: 'Font Awesome 6 Brands',
              value: '\uf13b',
            },
            {
              font: 'Font Awesome 6 Brands',
              value: '\uf38b',
            },
            {
              font: 'Font Awesome 6 Brands',
              value: '\uf3b9', 
            },
            {
              font: 'Font Awesome 6 Brands',
              value: '\uf41b', 
            },
          ],
        },
        size: {
          random: {
            enable: true,
            minimumValue: 25,
            maxValue: 35,
          },
          animation: {
            count: 0,
            enable: true,
            speed: 0.2,
            decay: 0,
            sync: true,
            destroy: 'none',
            startValue: 'random',
          },
        },
  },
  detectRetina: true,
  fpsLimit: 120,
  pauseOnBlur: true,
  pauseOnOutsideViewport: true,
  smooth: true,
}

Component Tehcnologies :

import styles from '../styles/Technologies.module.css'
import Image from 'next/image';

function Technologies() {
    return (
      <div id="technologies" className={styles.technologiescategory}>
            <p className={styles.title}>Technologies</p>
            <div className={styles.alltechnos}>
                <div className={styles.fronttechnos}>
                    <div className={styles.frontback}>
                        <p>Front-end</p>
                    </div>
                    <div className={styles.techno}>
                        <p>  <Image src="/images/html.png" width={45} height={50} />  </p>
                        <p className={styles.technoname}>HTML</p>
                    </div>
                    <div className={styles.techno}>
                        <p>  <Image src="/images/css.png" width={45} height={50} />  </p>
                        <p className={styles.technoname}>CSS</p>
                    </div>
                    <div className={styles.techno}>
                        <p>  <Image src="/images/javascript.png" width={45} height={50} />  </p>
                        <p className={styles.technoname}>Javascript</p>
                    </div>
                    <div className={styles.techno}>
                        <p>  <Image src="/images/react.png" width={43} height={45} />  </p>
                        <p className={styles.technoname}>React & React Native</p>
                    </div>
                    <div className={styles.techno}>
                        <p>  <Image src="/images/nextjs.png" width={43} height={45} />  </p>
                        <p className={styles.technoname}>Next.js</p>
                    </div>
                </div>
                <div className={styles.backtechnos}>
                    <div className={styles.frontback}>
                        <p>Back-end</p>
                    </div>
                    <div className={styles.techno}>
                        <p>  <Image src="/images/node.png" width={60} height={50} />  </p>
                        <p className={styles.technoname}>Node.js</p>
                    </div>
                    <div className={styles.techno}>
                        <p>  <Image src="/images/express2.png" width={50} height={50} />  </p>
                        <p className={styles.technonameexpress}>Express.js</p>
                    </div>
                    <div className={styles.techno}>
                        <p>  <Image src="/images/mongo2.png" width={50} height={50} />  </p>
                        <p className={styles.technonamemongo}>Mongodb</p>
                    </div>
                </div>
            </div>
      </div>
    );
  }
  
  export default Technologies;

And my page App :

import '../styles/globals.css';
import Head from 'next/head';
import Home from '../components/Home';
import Technologies from '../components/Technologies';

function App({ Component, pageProps }) {
  return (
    <>
      <Head>
        <title>Next.js App</title>
      </Head>
      <Home/>
      <Technologies/>
    </>
  );
}

export default App;

Sorry in advance for all these lines of codes.
Please let me know if you may need any other information.

Thank you very much for any help !
Capture d’écran 2024-01-09 à 16 34 19
Capture d’écran 2024-01-09 à 16 34 31

tsParticles Version

3.0.2

Code of Conduct

  • I agree to follow this project's Code of Conduct

Flickering Particles on projects build with React and Vite

I encountered an issue while using the example code provided in the @tsparticles/react library. The particles flicker – they disappear and reappear. This problem occurs in both Chrome and Firefox. In the case of Firefox, the particles seem to completely disappear. I am using React + Vite.

Convert the component using hooks

Since the main downloads of React are versions greater than 16.8.0, it can be dropped the support for older versions.

Converting the component using hooks gives smaller output and is more modern and up to date with latest changes.

This is a breaking change that needs to be done on dev branch, coming with v3 of the package.

Using loadTheme to dynamically change the background color crashes and freezes the whole page

Hello, love this package but running into problems with loadTheme. I want to be able to have one canvas and to be able to dynamically change the background and particle colors using a state change. However when using loadTheme it freezes the web page if I try to change background color (particle color is fine). I've simplified the code as much as possible and it still isn't working

const ParticleGallery = () => {
  const particlesInit = useCallback(async (engine: Engine) => {
    await loadFull(engine);
  }, []);

  const particlesLoaded = useCallback(
    async (container: Container | undefined) => {
      setTimeout(() => {
        container && container.loadTheme("theme_example");
      }, 3000);
    },
    []
  );

  return (
    <Particles
      id="tsparticles"
      init={particlesInit}
      loaded={particlesLoaded}
      options={{
        fpsLimit: 60,
        fullScreen: {
          enable: false,
          zIndex: 0,
        },
        background: {
          color: "#802129",
        },
        particles: {
          color: {
            value: "#000000",
          },
          number: {
            value: 40,
            density: {
              enable: true,
              value_area: 800,
            },
          },
          shape: {
            type: "square",
          },
          opacity: {
            value: 1,
            random: false,
          },
          size: {
            value: 300,
            random: true,
          },
          move: {
            enable: true,
            speed: 1,
            direction: "none",
            random: false,
            straight: true,
            out_mode: "out",
          },
        },
        interactivity: {
          detect_on: "window",
          events: {
            onHover: {
              enable: true,
              mode: "repulse",
            },
            onClick: {
              enable: true,
              mode: "push",
            },
            resize: true,
          },
          modes: {
            grab: {
              distance: 400,
              lineLinked: {
                opacity: 1,
              },
            },
            bubble: {
              distance: 500,
              size: 500,
              duration: 2,
              opacity: 1,
              speed: 3,
            },
            repulse: {
              distance: 200,
            },
            push: {
              particles_nb: 4,
            },
            remove: {
              particles_nb: 2,
            },
          },
        },
        themes: [
          {
            name: "theme_example",
            options: {
              background: {
                color: "#ffffff",
              },
              particles: {
                color: {
                  value: "#5F65FF",
                },
              },
            },
          },
        ],
        retina_detect: true,
      }}
    />
  );
};

Next JS

Thanks for the work!

Doesn't work in Next JS. Any chance you have some docs/examples of usages in Next JS?

I tried to do a dynamic import but then I don't have access to initParticlesEngine, when I try to do a dynamic import of that, it says it's a hook that cannot be used inside a useEffect.

Any help appreciated.

Fullscreen disable not functioning as expected

Hello!

I have disabled the fullscreen option and configured styling via CSS but nothing changes with the component, it continues to behave as if fullscreen is still enabled.

Here is the component:

import React, { useCallback } from 'react';
import Particles from 'react-tsparticles';
import { loadFull } from 'tsparticles';

const AntParticles = () => {
  const particlesInit = useCallback((engine) => {
    loadFull(engine);
  }, []);
  return (
    <Particles
      id="tsparticles"
      init={particlesInit}
      options={{
        fullscreen: {
          enable: false,
        },
        particles: {
          color: {
            value: '#000',
          },
          move: {
            direction: 'none',
            enable: true,
            outModes: {
              default: 'bounce',
            },
            random: false,
            speed: 3,
            straight: false,
          },
          number: {
            limit: 10,
            value: 0,
          },
          shape: {
            type: 'circle',
          },
          size: {
            value: 2,
          },
        },
        emitters: {
          direction: 'none',
          life: {
            count: 1,
            duration: 20,
          },
          rate: {
            quantity: 1,
            delay: 0.5,
          },
          size: {
            width: 0,
            height: 0,
          },
        },
      }}
    />
  );
};

export default AntParticles;

The CSS:

#tsparticles {
  position: absolute;
  width: 100%;
  height: 100%;
}

I'm sure it's something obvious I am missing but every combination of things I've tried has yielded the same behavior described above

hexagons preset is not working for me

I'm trying to use the tsParticles (specifically the react-tsparticles) with the latest version of Next.js so far, but when I copy and paste the particle.json e bind it to the <Particles/> component it doesn't behave as expected. All the particles moves fowards its relative position (very similar to the Hyperspace example) instead follow hexagon-shaped path.

Another weird issue that is happning is that is not following the background color from CSS (which also works with others presets)

The TSX files and the css doesn't seem to be the major problem because all other presets and examples works as expected.

How setup the particles.json file to produce the same effect as hexagon preset showed above?

My Component:

'use client'

import { useCallback } from "react";
import Particles from "react-tsparticles";
import { loadFull } from "tsparticles";
import type { Container, Engine } from "tsparticles-engine";

export function ParticleContainer() {
    const particlesInit = useCallback(async (engine: Engine) => {
        console.log(engine);
        await loadFull(engine);
    }, []);

    const particlesLoaded = useCallback(async (container: Container | undefined) => {
        await console.log(container);
    }, []);

    return (
        <Particles
            id="tsparticles"
            init={particlesInit}
            loaded={particlesLoaded}
            canvasClassName="particle-canvas"
            url="/particles.json"
        />
    );
}

My component use case:

import { ParticleContainer } from "../components/particles-container"

export default function About() {
    return (
        <main>
            <div id="carousel-container" className="carousel-container">
                <div id="home-carousel" className="">
                    <div className="carousel-inner">
                        <ParticleContainer/>
                        <div className="carousel-item active">
                            <div className="carousel-caption ">
                                <div className="text-center">
                                    <span className="align-middle">
                                        <h2>My Title</h2>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <section>
                <div className="container col-xxl-8 px-4 py-5">
                    <div className="">
                        <p className="main-text">
                            Content ... Lorem Ipsum... 
                        </p>
                    </div>
                </div>
            </section>
        </main>
    )
}

Example of the rendered page working just fine with other preset:

Example of the rendered page working just fine with other preset

Expected particle behaviour:

Expected particle behaviour

The current json provided by the option of exporting the hexagons preset (In my case I just switch the fullscreen to false):
https://pastebin.com/b8qnJyyG

Faulty behaviour:
Faulty behaviour

particles cover the whole page, i want it to only cover my hero component but its covering the whole page, im using next js

issue2
issue1

i want it to only cover the black background image but its stretchin over

this my code below for my hero component
"use client" import React from 'react'; import { useCallback } from "react"; import Particles from "react-tsparticles"; //import { loadFull } from "tsparticles"; // if you are going to use loadFull, install the "tsparticles" package too. import { loadSlim } from "tsparticles-slim"; // if you are going to use loadSlim`, install the "tsparticles-slim" package too.
import Image from 'next/image';

const Hero = () => {
const particlesInit = useCallback(async engine => {
console.log(engine);
// you can initiate the tsParticles instance (engine) here, adding custom shapes or presets
// this loads the tsparticles package bundle, it's the easiest method for getting everything ready
// starting from v2 you can add only the features you need reducing the bundle size
//await loadFull(engine);
await loadSlim(engine);
}, []);

const particlesLoaded = useCallback(async container => {
await console.log(container);
}, []);
return (


<Particles
id="tsparticles"
init={particlesInit}
loaded={particlesLoaded}
options={{
fullScreen: {},
fpsLimit: 120,
interactivity: {
events: {
onClick: {
enable: true,
mode: "push",
},
onHover: {
enable: true,
mode: "repulse",
},
resize: true,
},
modes: {
push: {
quantity: 4,
},
repulse: {
distance: 200,
duration: 0.4,
},
},
},
particles: {
color: {
value: "#ffffff",
},
links: {
color: "#ffffff",
distance: 150,
enable: true,
opacity: 0.5,
width: 1,
},
move: {
direction: "none",
enable: true,
outModes: {
default: "bounce",
},
random: false,
speed: 6,
straight: false,
},
number: {
density: {
enable: true,
area: 800,
},
value: 80,
},
opacity: {
value: 0.5,
},
shape: {
type: "circle",
},
size: {
value: { min: 1, max: 5 },
},
},
detectRetina: true,
height: 20,
}}
/>

  <div className=" grid grid-cols-2 gap-5 text-white p-[80px]  items-center">
    <div className="space-y-4">
      <h1 className="text-6xl font-bold">Buy And Sell Digital Currency</h1>
      <p>Bitcoins work just like obtaining any other currency. You can buy and sell them, and that is the future.</p>
      <button className="bg-green-500 hover:bg-white hover:text-black hover:border hover:border-green-500 text-white font-bold py-2 px-4 rounded transition-colors duration-300">
        Our Services
      </button>
    </div>
    <div className="flex justify-center">
      <Image
        src="/assets/hero.png"
        alt="Digital Currency"
        width={500}
        height={300}
        
      />
    </div>
  </div>
</div>
</main>

);
};

export default Hero;
`

and this my page.js
`
import Hero from "@/components/website/Hero";
import HowItWorks from "@/components/website/HowItWorks";

export default function WebPage() {
return (

      <Hero />

      <HowItWorks/>
</main>
);

}`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.