linkedin Skip to Main Content
Just announced: We now support interviewing in spreadsheets!
Back to blog

How to Create Interactive Animated Backgrounds in React with tsParticles

Development

Adding animations to a site is a great way to make it stand out on the web, even better when it’s interactive. However, depending on the complexity, achieving these effects can require a lot of time and experience. 

Unless, of course, you utilize tsParticles

This lightweight library helps you build stunning interactive animations with a few lines of code. It includes customization features that help you achieve animations far more advanced than just floating particles on the screen:

Source: Matteo Bruni

In this tutorial, we will show you how to use tsParticles in React to create interactive animated backgrounds. To follow along, you should be familiar with React and have Node installed on your system.

✅You can use the CoderPad sandboxes located throughout this page or as a new browser window to run the code in this tutorial.

Introduction to tsParticles

tsParticles is a successor of particles.js, an older library with similar functionality whose development is no longer active. It is backward-compatible with particles.js and has similar configuration options, so you can easily migrate from one to the other. 

tsParticles has lots of new features, like first-party integrations with leading frameworks, a frame per second (fps) limiter so as not to overwork the CPU, and the ability to use Font Awesome icons and images as particles.

tsParticles might take some time to get used to due to the numerous configuration options available for creating your desired particle animation. To help with this we will be exploring a few particle animations you can create with this library.

Get started by setting up React and tsParticles 

For some of the popular frameworks there are ready-to-use tsParticle components available. In our case, we will be using the official tsParticles React component. We will also use tsParticles Full Bundle, which has more features available than the tsParticles Slim Bundle.

Type in the following command in the terminal to set up a React app, install the needed dependencies, and start up the development server.

npx create-react-app particle-background
cd particle-background
npm i react-particles tsparticles
npm start

Now let’s initialize tsParticles and render the Particles component in the src/App.js file. Here is what the file will look like:

import Particles from "react-tsparticles";
import { loadFull } from "tsparticles";
import { useCallback } from "react";

const App = () => {
  const options = {
    //...
  };
 
  const particlesInit = useCallback(async (engine) => {
    await loadFull(engine);
  }, []);

  return (
    <div className="App">
      <Particles options={options} init={particlesInit} />
    </div>
  );
};

export default AppCode language: JavaScript (javascript)

The Particles component accepts several properties among which is the options prop. This is where we will be passing the configurations for creating the particle animation.

Understand the configuration options

To demonstrate how the configuration options work, we’ll start with this example created by Matteo Bruni. It features a particle animation with floating circles in the brand colors of the popular communication software Slack. The circles link together when they get close to each other and link with a nearby mouse hover. A click creates an extra four particles. 

Here are the configuration options: 

const options = {
    particles: {
      number: {
        value: 80,
        density: {
          enable: true,
          area: 800
        }
      },
      color: {
        value: ["#2EB67D", "#ECB22E", "#E01E5B", "#36C5F0"]
      },
      shape: {
        type: "circle"
      },
      opacity: {
        value: 1
      },
      size: {
        value: { min: 1, max: 8 }
      },
      links: {
        enable: true,
        distance: 150,
        color: "#808080",
        opacity: 0.4,
        width: 1
      },
      move: {
        enable: true,
        speed: 5,
        direction: "none",
        random: false,
        straight: false,
        outModes: "out"
      }
    },
    interactivity: {
      events: {
        onHover: {
          enable: true,
          mode: "grab"
        },
        onClick: {
          enable: true,
          mode: "push"
        }
      },
      modes: {
        grab: {
          distance: 140,
          links: {
            opacity: 1
          }
        },
        push: {
          quantity: 4
        }
      }
    }
  };Code language: JavaScript (javascript)

Here is the result of the above configs:

There are lots of different options that go into the animation–most of them are self-explanatory from their names. But if you’re unfamiliar they might still seem a bit perplexing. Here are two in particular that often cause confusion:

  • particles: This option handles everything that has to do with the display and behavior of the particles. In the above config, we set the number of particles, their colors, the shape (“circle”), as well as the particles’ opacity, size range, and movement type. We also set the details of the links, which are the lines connecting the particles when they are close.
  • interactivity: This option controls what happens when click and hover events are triggered, and when a particle intersects with a div element. In the above config, when a hover occurs we are calling the grab mode which links nearby particles. When a click occurs we call the push mode which adds four more particles.

There are even more options and properties than we covered above, all of which can be explored in the official documentation and by playing around with the available demos.

Create more advanced effects using the Emitters and Absorbers plugins

As the name implies, emitters are for releasing/giving off particles while absorbers are for absorbing particles. These are advanced options that can be used to create particle animation like confetti, fireworks, black hole effects, and more. 

The docs don’t currently include helpful information regarding these options – but you can figure out how they work from the available demos that I’ve outlined below. 

Let’s create a black hole animation where particles are released using emitters and sucked up using absorbers. Here is a GIF showing what we want to create.

Black hole effect

Start by adding the configurations using the particles option. We will make the particles: 

  • Be a circle
  • Be semi-transparent (opacity
  • Have random colors and sizes within a set range
  • Bounce when they hit the side of the page 
const options = {
    background: {
      color: "#fff",
    },
    particles: {
      shape: {
        type: "circle"
      },
      number: {
        value: 0
      },
      color: {
        value: "random"
      },
      opacity: {
        value: 0.3
      },
      size: {
        value: {min: 5, max: 20}
      },
      move: {
        enable: true,
        speed: 6,
        random: false,
        outModes: "bounce",
      }
    },
  };Code language: JavaScript (javascript)

Since we have set number.value to 0, no particle will be displayed on the screen. This is exactly what we want since we want all particles to come from the emitter. Now let’s add the emitters option.

const options = {
  // …
    emitters: [
      {
        direction: "top-right",
        position: {
          x: 0,
          y: 100
        },
        rate: {
          delay: 0.3,
          quantity: 4,
        },
      },
    ]
  };Code language: JavaScript (javascript)

The above will create an emitter position at the bottom left of the screen which releases particles to the top-right direction at the rate of 4 particles every 0.4 seconds.

Emitter in action

If we wanted, we could easily create another emitter by adding another object within the emitters array property. Particles emitted by the added emitters will be the same as the first since they are both working with the same particles option. To change the emitted particles, we can define a particles property within the new emitter object.

Now to add an absorber at the middle of the screen with a size that changes as particles are absorbed, add the following configuration within the options object:

const options = {
   // …
    absorbers: [
      {
        position: { x: 50, y: 50 },
        size: {
          value: 50,
          limit: 100,
        }
      }
    ],
  };Code language: JavaScript (javascript)

With this the intended particle animation has been achieved. We can view it and its configurations below:

Make the most of presets

Rather than creating a particle animation from scratch, we can use the official presets or use the configurations from the available demos and then do some fine-tuning to achieve our desired effect.

To show how we can use the official presets, we’ll be using the confetti preset. 

First, let’s install the preset package using the following command:

npm i tsparticles-preset-confetti

Now to load the preset, we need to modify the src/App.js file to look like the following:

import Particles from "react-tsparticles";
import { loadFull } from "tsparticles";
import { useCallback } from "react";
import { loadConfettiPreset } from "tsparticles-preset-confetti";

const App = () => {
  const options = {
    preset: "confetti",
  };
 
  const particlesInit = useCallback(async (engine) => {
    await loadConfettiPreset(engine)
    await loadFull(engine)
  }, []);

  return (
    <div className="App">
      <Particles options={options} init={particlesInit} />
    </div>
  );
};

export default AppCode language: JavaScript (javascript)

Above in options , we specified the preset by its name using the preset option. Then we loaded in the callback function passed to the init prop. Below is the result:

To customize the preset like changing the background color, increasing the number of particles emitted, changing the particle shape, etc, we can just add other options to the options object. 

For example, to change the color of the confetti, here is what the configuration options look like:

const options = {
    particles: {
      color: {
        value: ["#0000ff", "#00ff00"],
      },
    },
    preset: "confetti",
  };Code language: JavaScript (javascript)

Explore other customization plugins 

tsParticles allows even more advanced customization through plugins, which can be used to create custom shapes and presets using the addShape and addPreset method respectively.

Let’s look at how we can use the addShape method to create a pentagon and use it to replace the circles emitted in the black hole example above. 

const loadPentagonShape = (engine) => {
  engine.addShape("pentagon", (context, particle, radius) => {
    const angle = (2 * Math.PI) / 6;
    context.beginPath();
    for (let i = 0; i < 5; i++) {
      context.lineTo(
        radius * Math.cos(angle * i),
        radius * Math.sin(angle * i)
      );
    }
    context.closePath();
    context.stroke();
  });
};Code language: JavaScript (javascript)

The addShape method accepts multiple arguments, but the most important is the shape name and the draw function callback.. 

The draw function callback helps you create your desired shape, and we’ve passed multiple arguments to it to help us tweak the shape that is being drawn.

  • context is the HTML canvas context 
  • particle contains the value of the properties passed in the particles options, discussed above 
  • radius , as the name implies, is the radius of the shape.

Now, to make the pentagon shape available for use, you need to call it before the loadFull function is called and our tsParticles are initialized, like this:

const particlesInit = useCallback(async (engine) => {
    loadPentagonShape(engine)
    await loadFull(engine)
  }, []);Code language: JavaScript (javascript)

With this, you can start using this shape by passing its name as a value to shape.type in the particles option. Below is the result of using this shape in the black hole example:

As mentioned earlier, tsParticles also allows us to create our own presets using the addPreset method, which takes in the preset name and configuration options as arguments. In the same way we created a custom shape, we also need to create a load which will be called to make the preset available for use.

const options = {
  // preset options
};

const loadCustomPreset = (engine) => {
  engine.addPreset("customPreset", options);
};Code language: JavaScript (javascript)

Using a custom preset is exactly the same as using an official one, where you need to call the preset before initializing tsParticles and specify the preset name in the preset option of the particle configurations.

Play with tsParticles in the CoderPad sandbox

tsParticles makes it easier than ever before to create and customize particle animations for your website. In my view, it’s pretty great!  Try implementing some of the tricks you learned today in the CoderPad sandbox

Taminoturoko Briggs is an enthusiastic software developer and technical writer. Core languages include JavaScript and Python.