tsParticles tutorial
Tags: typescript, javascript, tutorial, webdev
Published: 2020-06-10 11:00:00


# How to add tsParticles in your website

Have you seen particles effect in some websites and you want one too?

Do you have particles.js installed but it have problems or it's too heavy for your users?

Are you searching a new animation for your website?

Well, you are in the right place. `tsParticles` is a new library, started from the particles.js codebase, to have some particles animations in your website.

[![jsDelivr](https://data.jsdelivr.com/v1/package/npm/tsparticles/badge)](https://www.jsdelivr.com/package/npm/tsparticles) [![Cdnjs](https://img.shields.io/cdnjs/v/tsparticles)](https://cdnjs.com/libraries/tsparticles) [![npmjs](https://badge.fury.io/js/tsparticles.svg)](https://www.npmjs.com/package/tsparticles) ![npm](https://img.shields.io/npm/dm/tsparticles) [![Nuget](https://img.shields.io/nuget/v/tsParticles)](https://www.nuget.org/packages/tsParticles/)

{% github matteobruni/tsparticles %}

Let's start with the installation

## Setup

### Download

You can download the file from [GitHub releases](https://github.com/matteobruni/tsparticles/releases)

![Release page preview](https://dev-to-uploads.s3.amazonaws.com/i/94ffh7hbwh7q2044onzw.png)

You should have opened a page like the one above, click on the latest release link if you need more informations or just click the `tsparticles.min.js` file to view it and you can download it.

You can place it anywhere in your website.

For example you can use a `js` folder, add the file there and create the `script` tag like this:

```html
<script type="text/javascript" src="js/tsparticles.min.js"></script>
```

#### Slim file

Probably you have seen a `tsparticles.slim.min.js`, a lighter version of tsParticles.
It's missing some features from the full library:

- Absorbers
- Emitters
- Polygon Mask

These features will be discussed later, if you don't need them you can use the slim version.

### CDN

If you want to use a CDN to link the library, or use them to download the files here are the instructions

#### cdnjs

Let's start with the most famous and used.

![cdnjs page](https://dev-to-uploads.s3.amazonaws.com/i/kc2ymglp7ajribme31l4.png)

Here you can find all files, don't worry about all those files, you just need `tsparticles.min.js` (or the slim version)


![cdnjs download](https://dev-to-uploads.s3.amazonaws.com/i/ferj0gacl14d3710p5g6.png)

The file is marked as default, you can just copy the url or expanding the menu you can copy all the `script` tag.

I suggest you to use the tag with the integrity check (Copy Script Tag option).

#### jsDelivr

Another famous CDN is supported too and this is easy to use too.

![jsDelivr download page](https://dev-to-uploads.s3.amazonaws.com/i/wtdxsbene5uukz55mwon.png)

Just copy the script tag (I recommend the integrity check) and you're ready to include it in your page.

### NPM

If you are using NPM you can simply run one of these commands

```shell
npm install tsparticles
```

or 

```shell
yarn add tsparticles
```

And you have it ready in your `node_modules` folder.

### Wrappers

This project have also some official wrappers for some Javascript frameworks to easily use and configure this library

#### jQuery

![npm](https://img.shields.io/npm/v/jquery-particles) ![npm](https://img.shields.io/npm/dm/jquery-particles)

If you want to use tsParticles with jQuery checkout [this repository](https://github.com/matteobruni/jquery-particles)

{% github matteobruni/jquery-particles %}

#### VueJS

![npm](https://img.shields.io/npm/v/particles.vue) ![npm](https://img.shields.io/npm/dm/particles.vue)

If you want to use tsParticles with VueJS checkout [this repository](https://github.com/matteobruni/particles.vue)

{% github matteobruni/particles.vue %}

#### ReactJS

![npm](https://img.shields.io/npm/v/react-tsparticles) ![npm](https://img.shields.io/npm/dm/react-tsparticles)

If you want to use tsParticles with ReactJS checkout [this repository](https://github.com/matteobruni/react-tsparticles)

{% github matteobruni/react-tsparticles %}

#### Preact

![npm](https://img.shields.io/npm/v/preact-particles) ![npm](https://img.shields.io/npm/dm/preact-particles)

If you want to use tsParticles with Preact checkout [this repository](https://github.com/matteobruni/preact-particles)

{% github matteobruni/preact-particles %}

#### Angular CLI

![npm](https://img.shields.io/npm/v/ng-particles) ![npm](https://img.shields.io/npm/dm/ng-particles)

If you want to use tsParticles with Angular CLI (actually v9) checkout [this repository](https://github.com/matteobruni/ng-particles)

{% github matteobruni/ng-particles %}

### Usage

First of all you need to find the `tsparticles.min.js` downloaded with the instructions above.

Once you are ready with the `script` tag included you have two option to start using tsParticles.

#### Javascript Object

You can use a Javascript object containing all options like this

```javascript
let options = { /* omitted for brevity, I'll describe the options later */};

tsParticles.load('<element id>', options);
//<element id> is a placeholder sample, use it without <>
```

#### External Json File

Otherwise you can use an external JSON file, it's easier to maintain because you need to change only this file and not your scripts that could be minified or something like that.

The JSON file is loaded like this

*particles.json*
```javascript
{
    // omitted for brevity, I'll describe all the options later
}
```

*app.js*
```javascript
tsParticles.loadJSON('<element id>', 'particles.json');
//<element id> is a placeholder sample, use it without <>
```

### Particles Manager object

`load` and `loadJSON` methods returns a `Promise<Container>` object, the `Container` object is the object containing the canvas, the particles and all is needed to work.

You can access it using the method `tsParticles.dom()` which returns a `Container[]` with all containers initialized or `tsParticles.domItem(index)` which returns the specified `Container` if found, `index` is the array index, just a managed version of `tsParticles.dom()[index]`.

If you want to unwrap the `Promise` you can await the load methods if you are using an async function or use the `then` method (Official API [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then)).

Let's see a sample of `then` method:

*app.js*
```javascript
tsParticles.load('<element id>', { /* omitted for brevity */ }).then(function (container) {
  // container is ready to be used
});
```

The container object is really useful if you want to make particles more interactive or customizable.

##### Properties

`options`: The current options loaded in the object, some changes to this object can be effective only after a `refresh()`

##### Methods

`play(force)`: Starts the animations or resume from `pause`, `force` is an optional boolean parameter to force the animation. This method doesn't allocate resources, just plays the animations.

`pause()`: Pauses the animations. This method doesn't clean any resource, just pauses the animations.

`start()`: Starts the container, reallocates all the resources freed by `stop`. Can't start after `destroy`.

`stop()`: Stops the container, frees unneeded resources.

`destroy()`: Destroys the container and invalidates it. The container will be unusable after this, any method called on it can return an error.

`refresh()`: This methods is a shorthand of `stop`/`start` cycle. This method is good to reload options changed by code.

`exportImage(callback, type, quality)`: Exports the current canvas image, `background` property of `options` won't be rendered because it's css related. The `callback` is a function that handles the exported image, `type` is the image type you want to export and `quality` the quality of the image, these two parameters are optional.

`exportConfiguration()`: Exports the current configuration using `options` property returning a JSON string representing the `options` object.

`draw()`: Draws a single frame of animation, if you want to handle it yourself just `pause` the container and call `draw` when you need it.

`getAnimationStatus()`: Returns a boolean with the animation status, `true` is playing, `false` is paused

`setNoise(noise)`: Customize noise generation with a `noise` object (three functions: `generate`, `init`, `update`)

`setNoise(generator, init, update)`: Customize noise generation with a `noise` object destructured. The `generator` is a function taking a `particle` object and returning a `noise value` object (two properties: `angle` and `length`) that will be applied to `particle` movement. The `init` function is called in `start` method. The `update` function is called after all `particles` has been moved.

### Options

Let's dive inside the options with some samples.

#### Default Values

```json
{
  "background": {
  },
  "backgroundMask": {
    "cover": {
      "color": {
        "value": "#fff"
      },
      "opacity": 1
    },
    "enable": false
  },
  "detectRetina": true,
  "fpsLimit": 30,
  "infection": {
    "cure": false,
    "delay": 0,
    "enable": false,
    "infections": 0,
    "stages": []
  },
  "interactivity": {
    "detectsOn": "canvas",
    "events": {
      "onClick": {
        "enable": false,
        "mode": []
      },
      "onDiv": {
        "ids": [],
        "enable": false,
        "mode": [],
        "type": "circle"
      },
      "onHover": {
        "enable": false,
        "mode": [],
        "parallax": {
          "enable": false,
          "force": 2,
          "smooth": 10
        }
      },
      "resize": true
    },
    "modes": {
      "bubble": {
        "distance": 200,
        "duration": 0.4
      },
      "connect": {
        "distance": 80,
        "links": {
          "opacity": 0.5
        },
        "radius": 60
      },
      "grab": {
        "distance": 100,
        "links": {
          "opacity": 1
        }
      },
      "push": {
        "quantity": 4
      },
      "remove": {
        "quantity": 2
      },
      "repulse": {
        "distance": 200,
        "duration": 0.4,
        "speed": 1
      },
      "slow": {
        "factor": 3,
        "radius": 200
      }
    }
  },
  "particles": {
    "collisions": {
      "enable": false,
      "mode": "bounce"
    },
    "color": {
      "value": "#fff",
      "animation": {
        "enable": false,
        "speed": 1,
        "sync": true
      }
    },
    "links": {
      "blink": false,
      "color": {
        "value": "#fff"
      },
      "consent": false,
      "distance": 100,
      "enable": false,
      "opacity": 1,
      "shadow": {
        "blur": 5,
        "color": {
          "value": "lime"
        },
        "enable": false
      },
      "triangles": {
        "enable": false
      },
      "width": 1,
      "warp": false
    },
    "move": {
      "attract": {
        "enable": false,
        "rotate": {
          "x": 3000,
          "y": 3000
        }
      },
      "direction": "none",
      "enable": false,
      "noise": {
        "delay": {
          "random": {
            "enable": false,
            "minimumValue": 0
          },
          "value": 0
        },
        "enable": false
      },
      "outMode": "out",
      "random": false,
      "speed": 2,
      "straight": false,
      "trail": {
        "enable": false,
        "length": 10,
        "fillColor": {
          "value": "#000000"
        }
      },
      "vibrate": false,
      "warp": false
    },
    "number": {
      "density": {
        "enable": false,
        "area": 800,
        "factor": 1000
      },
      "limit": 0,
      "value": 100
    },
    "opacity": {
      "animation": {
        "enable": false,
        "minimumValue": 0,
        "speed": 2,
        "sync": false
      },
      "random": {
        "enable": false,
        "minimumValue": 1
      },
      "value": 1
    },
    "rotate": {
      "animation": {
        "enable": false,
        "speed": 0,
        "sync": false
      },
      "direction": "clockwise",
      "random": false,
      "value": 0
    },
    "shadow": {
      "blur": 0,
      "color": {
        "value": "#000000"
      },
      "enable": false,
      "offset": {
        "x": 0,
        "y": 0
      }
    },
    "shape": {
      "options": {},
      "type": "circle"
    },
    "size": {
      "animation": {
        "destroy": "none",
        "enable": false,
        "minimumValue": 0,
        "speed": 5,
        "startValue": "max",
        "sync": false
      },
      "random": {
        "enable": false,
        "minimumValue": 1
      },
      "value": 3
    },
    "stroke": {
      "color": {
        "value": "#ff0000"
      },
      "width": 0,
      "opacity": 1
    },
    "twinkle": {
      "lines": {
        "enable": false,
        "frequency": 0.05,
        "opacity": 1
      },
      "particles": {
        "enable": false,
        "frequency": 0.05,
        "opacity": 1
      }
    }
  },
  "pauseOnBlur": true
}
```

All these values are not required to be used in your config, these are the starting values that will be merged with your customizations.

You can find all informations about options in the official wiki here

https://github.com/matteobruni/tsparticles/wiki/tsParticles-Options

#### Samples

We can see that everything is disabled except the retina screen detection and the pause on window blur. So if you specify an empty config you'll have `100` unlinked particles that are not moving and without any interaction.

{% codepen https://codepen.io/matteobruni/pen/dyGGWBG %}

*A little note, the black background is set by css because particles are white by default.*

---

We can start with a config where particles are moving

```json
{
  "particles": {
    "move": {
      "enable": true
    }
  }
}
```

{% codepen https://codepen.io/matteobruni/pen/PoZZmMK %}

---

Maybe we want smaller particles?

```json
{
  "particles": {
    "move": {
      "enable": true
    },
    "size": {
      "value": 2
    }
  }
}
```

{% codepen https://codepen.io/matteobruni/pen/ZEQQybZ %}

---

What if we want links between particles?

```json
{
  "particles": {
    "links": {
      "enable": true
    },
    "move": {
      "enable": true
    },
    "size": {
      "value": 2
    }
  }
}
```

{% codepen https://codepen.io/matteobruni/pen/abddwNz %}

---

Who doesn't like a little semi-transparency?

```json
{
  "particles": {
    "links": {
      "enable": true,
      "opacity": 0.5
    },
    "move": {
      "enable": true
    },
    "opacity": {
      "value": 0.5
    },
    "size": {
      "value": 2
    }
  }
}
```

{% codepen https://codepen.io/matteobruni/pen/eYJJRvq %}

---

What about some color?

```json
{
  "particles": {
    "color": {
      "value": "#000"
    },
    "links": {
      "color": {
        "value": "#000"
      },
      "enable": true,
      "opacity": 0.5
    },
    "move": {
      "enable": true
    },
    "opacity": {
      "value": 0.5
    },
    "size": {
      "value": 2
    }
  }
}
```

{% codepen https://codepen.io/matteobruni/pen/poggwrB %}

*A little note, These particles are black, I removed the css background color in the sample.*

---

Let's start with some interactivity:

```json
{
  "interactivity": {
    "events": {
      "onHover": {
        "enable": true,
        "mode": "bubble"
      }
    }
  },
  "particles": {
    "color": {
      "value": "#000"
    },
    "links": {
      "color": {
        "value": "#000"
      },
      "enable": true,
      "opacity": 0.5
    },
    "move": {
      "enable": true
    },
    "opacity": {
      "value": 0.5
    },
    "size": {
      "value": 2
    }
  }
}
```

{% codepen https://codepen.io/matteobruni/pen/poggrov %}

---

The interaction is almost invisible, can we customize it?

```json
{
  "interactivity": {
    "events": {
      "onHover": {
        "enable": true,
        "mode": "bubble"
      }
    },
    "modes": {
      "bubble": {
        "opacity": 0.8,
        "size": 10,
        "color": {
          "value": "#ff0000"
        }
      }
    }
  },
  "particles": {
    "color": {
      "value": "#000"
    },
    "links": {
      "color": {
        "value": "#000"
      },
      "enable": true,
      "opacity": 0.5
    },
    "move": {
      "enable": true
    },
    "opacity": {
      "value": 0.5
    },
    "size": {
      "value": 2
    }
  }
}
```

{% codepen https://codepen.io/matteobruni/pen/GRoovJY %}

---

Maybe something that happens on mouse click?

```json
{
  "interactivity": {
    "events": {
      "onHover": {
        "enable": true,
        "mode": "bubble"
      },
      "onClick": {
        "enable": true,
        "mode": "push"
      }
    },
    "modes": {
      "bubble": {
        "opacity": 0.8,
        "size": 10,
        "color": {
          "value": "#ff0000"
        }
      }
    }
  },
  "particles": {
    "color": {
      "value": "#000"
    },
    "links": {
      "color": {
        "value": "#000"
      },
      "enable": true,
      "opacity": 0.5
    },
    "move": {
      "enable": true
    },
    "opacity": {
      "value": 0.5
    },
    "size": {
      "value": 2
    }
  }
}
```

{% codepen https://codepen.io/matteobruni/pen/vYLLJqw %}

---

That's it, all you need to do is try all the possible combinations with all the options.

---

All samples used in this article can be found here

https://codepen.io/collection/APZZqm

Other advanced samples can be found here

https://codepen.io/collection/DPOage

There's also an official demo page where you can easily edit the configurations and try them to create a preset that you like:

https://particles.matteobruni.it