Home

Awesome

Sparticles

javascript particles in canvas

https://sparticlesjs.dev

Lightweight, High Performance Particles in Canvas.
<sup>For those occasions when you 👏 just 👏 gotta 👏 have 👏 sparkles, snow, or stars on your homepage!</sup>

Image of little coloured stars known as "Sparticles" running at 120fps



installation

Depending on how your project looks,

vanilla

  1. firstly make sure you've downloaded the latest version of the script to your application directory (if you are running on a CMS you might also need to upload the file to your server). The file you'll want to use is; dist/sparticles.min.js to make sure it downloads the fastest for your users.

  2. After you've downloaded, or uploaded, the sparticles.min.js file to the correct place, you'll then need to include it in your web page;

<script src="../path/to/sparticles.min.js"></script>
  1. And finally, you should then be able to initialise the Sparticles by running this code in your javascript;
    <sup>(make sure this code runs after you've included the script above.)</sup>
<script>
  window.onload = function() {
    let myElement = document.getElementById("myDiv");
    let mySparticles = new Sparticles(myElement, { count: 100 }, 400);
  }
</script>

jquery

For jQuery sites, you may follow all of the steps above, but replace the third step with something like below;

<script>
  let $el = $("#myDiv");
  let mySparticles = new Sparticles($el[0], { count: 100 }, 400);
</script>

app / bundler

If you're running a more modern type of application with something like Svelte or VueJs;

  1. First you will want to install the module with NPM;
yarn add --dev sparticles
# or npm, if you prefer
npm install --save-dev sparticles
  1. Then import the module in to the app where you want to use it
import Sparticles from "sparticles";
  1. Finally initialise with vanillaJS
new Sparticles(node, { count: 100 }, 400);
  1. If you're using SvelteJS specifically, then your single-file component would look a little like this;
<script>

  import Sparticles from "sparticles";

  let sparticles,
      options = { color: "gold", shape: "star", speed: 50 };

  function addSparticles(node) {
    new Sparticles(node, options, 400);
  }

</script>

<main use:addSparticles>
</main>

usage

Providing that the script/module has been properly included, then it can be initialised by running the Sparticles() constructor;

let mySparticles = new Sparticles();

parameters

When initialising the Sparticles instance there are some parameters that can be supplied.

parametertypedefaultdescription
nodeHTMLElementdocument.bodythe element in the DOM which the Sparticles will append to
optionsObject{}an object with all the options for the instance
widthNumbernode.clientWidththe width of the canvas element
heightNumbernode.clientWidththe height of the canvas element (defaults to width)

<sup>Leave the width/height properties empty to make the canvas resize to fit it's node</sup>


let mySparticles = new Sparticles();
let mySparticles = new Sparticles(document.getElementById("myDiv"));
let mySparticles = new Sparticles({ color: "red" });
let mySparticles = new Sparticles({ color: "red" }, 400, 300);

options

A brief look at all the options, with more details below.

optiontypedefaultdescription
compositionStringsource-overcanvas globalCompositeOperation value for particles
countNumber50number of particles on the canvas simultaneously
speedNumber10default velocity of every particle
parallaxNumber1speed multiplier effect for larger particles (0 = none)
directionNumber180default direction of particles in degrees (0 = ↑, 180 = ↓)
xVarianceNumber2random deviation of particles on x-axis from default direction
yVarianceNumber2random deviation of particles on y-axis from default direction
rotateBooleantruecan particles rotate
rotationNumber1default rotational speed for every particle
alphaSpeedNumber10rate of change in alpha over time
alphaVarianceNumber1random deviation of alpha change
minAlphaNumber0minumum alpha value of every particle
maxAlphaNumber1maximum alpha value of every particle
minSizeNumber1minimum size of every particle
maxSizeNumber10maximum size of every particle
bounceBooleanfalseshould the particles bounce off edge of canvas
driftNumber1the "driftiness" of particles which have a horizontal/vertical direction
glowNumber0the glow effect size of each particle
twinkleBooleanfalseparticles to exhibit an alternative alpha transition as "twinkling"
styleStringfillfill style of particles (one of; "fill", "stroke" or "both")
shapeString/Arraycircleshape of particles (any of; circle, square, triangle, diamond, line, image) or "random"
colorString/Arrayrandomcss color as string, or array of color strings (can also be "random")
randomColorFunctionrandomHsl()function for returning a random color when the color is set as "random"
randomColorCountNumber3number of random colours when the color is set as "random"
imageUrlString/Arrayif shape is "image", define an image url (can be data-uri, should be square (1:1 ratio))

composition

The global render composition when rendering particles on top of one-another. This, however, is a very expensive operation when set to anything other than the default value (source-over), and will ultimately degrade performance, especially with many particles.

Will accept any of the values that are provided as part of the Canvas API

count

Simply the number of particles drawn to the screen.
Values over 500 may begin to degrade performance.

speed

The base value of speed across all particles. This is modified by options such as parallax and [x/y]Variance to determine the final velocity of each individual particle. A speed of 0 will render particles stationary before applying [x/y]Variance.

parallax

A value to apply more speed to larger particles, and less speed to smaller particles, creating an effect which makes larger particles appear closer to the screen.

direction

The base angle (in degrees) at which the particles are travelling, so long as they have a speed value.

xVariance

How much variance is applied between particles on the X axis. A value of 0 will make all particles appear to be going completely parallel, and look unnatural.

Can be used in conjunction with speed: 0; to make particles which float randomly in space.

yVariance

How much variance is applied between particles on the Y axis. A value of 0 will make all particles appear to be going completely parallel, and look unnatural.

Can be used in conjunction with speed: 0; to make particles which float randomly in space.

rotate

Toggle whether the particles are allowed to spin about their axis.

rotation

How fast the particles can spin about their axis, this has a random multiplier added per-particle which prevents a completely unnatural spinning effect.

alphaSpeed

Rate of change for the alpha value of all particles. A higher value will encourage the particles to flicker like candle lights. A value of 0 will disable alpha change.

alphaVariance

How much variance is applied between each particle on the alpha value change over time. A value of 0 will cause all particles to change alpha at the same rate, a higher value will introduce more variety.

minAlpha

The minimum alpha value a particle can change to. The lower the number the longer it will stay invisible on the canvas, this could be useful in some scenarios where the particle should fade out for a while.

Must be lower than the maxAlpha value.

maxAlpha

The maximum alpha value a particle can change to. The higher the number the longer it will stay visible on the canvas, this could be useful in some scenarios where the particle should stay at max alpha for a time.

Must be higher than the minAlpha value.

minSize

Minimum size (in pixels) of the particles. The actual size of each particle is variable between the minSize and maxSize. If the minSize and maxSize are the same value; then all particles will be uniformly sized.

maxSize

Maximum size (in pixels) of the particles. The actual size of each particle is variable between the minSize and maxSize. If the minSize and maxSize are the same value; then all particles will be uniformly sized.

style

Particles can be either stroked (outline) or filled (solid) and this setting determines that style. It's also possible to randomize the style by choosing "both"

bounce

Determine if particles should bounce off the boundaries of the canvas instead of resetting to the opposite side. This is best used with speed: 0; and a high value for [x/yVariance] to create a chaotic effect.

drift

How much a particle will "drift" as it falls. This is to imply a floatiness/wind effect like seen with snow flakes, or leaves. The drift will only apply if speed > 0 and direction is near to a 90degree value (0, 90, 180, 270)

glow

Glow (or shadow) effect around the particle. This will not affect images.

twinkle

Apply a "twinkle" effect to the particle when changing alpha. This works best with a higher alphaSpeed and alphaVariance value.

color

A CSS/HTML color string to apply across all particles.
If an array of colors ([ "#ff0", "red", "hsl(10,50%,50%)" ]) is given, then each particle will be assigned a random color from the array. Additionally "random" can be used to assign any random color.

randomColor

Custom function to use when generating random colors. The default function will return a fairly pleasant hsl() color with a high saturation and medium lightness. This can be overridden to suit your environment better. The two arguments (index, total) are Integers and allow for a little psuedo-randomizing.

example:

randomColor: function( index, total ) {
	return `hsl( ${index}, 80%, ${total - index}% )`;
}

randomColorCount

How many random colors to generate when color is random. The more colors generated the more chance there is of a performance penalty. It should be OK up to 50.

shape

Determine the shape of all the particles.
If an array of shapes ([ "circle", "star", "diamond" ]) is given, then each particle will be assigned a random shape form the array. Additionally "image" can be used to define a custom particle shape from an image when combined with imageUrl.

imageUrl

Determine the custom image to be used for all the particles. If an array of urls ([ "http://my.image/shape.png", "http://my.svg/shape.svg" ]) is given, then each particle will be assigned a random image as it's shape from the array. <sup>This image should be a square (1:1)</sup>

methods

a few public methods can be accessed by storing a reference to the Sparticles instance and executed like so;

let mySparticles = new Sparticles();
mySparticles.destroy();
methoddescription
destroy()destroy the Sparticles instance and remove event listeners
setCanvasSize( width, height )set the new size of the canvas
resetSparticles()reset all the particles on the canvas

styling

If the Sparticles are simply going to be placed in a container (like a <div>) then the only styling that should be necessary is to set the width/height of the canvas using the width and height parameters.


To place the Sparticles in the background of a web-page, you'll need to add a container to the <body> which the canvas can sit in, then position it fixed:

<html>
  <body>
    <!-- your html web page content -->
    <div class="sparticles-container"></div>
  </body>
</html>

Then we set up the CSS styling for the Sparticles container depending on our situation:

/** 
  * we need to make sure the background doesn't have a
  * background color as we want to place the container
  * behind it on the z-axis!
  */
html { background: black; }
body { background: transparent; }

.sparticles-container {
  position: fixed;
  left: 0; right: 0;
  top: 0; bottom: 0;
  /**
   * z-index: -1; this makes the <body> still interactive 
   * by placing the sparticles behind the content
   */
  z-index: -1; 
}
/**
* we could a;so use "pointer-events: none;" in
* modern browsers to put the particles on top of all our content
*/
@supports ( pointer-events: none ) {
  .sparticles-container {
    z-index: 2;
    pointer-events: none;
  }
}

Finally we can initiate the Sparticles with the .sparticles-container as the DOM element it's bound to:

let container = document.querySelector(".sparticles-container");
let mySparticles = new Sparticles( container, { color: "red" });
// no need for width/height as the  canvas will fill 
// the container which is fixed to the viewport size

performance

Sparticles is really quite fast!

It was designed to be the smallest (within reason) and fastest performing particles script with such a large feature set!

Some other popular particle scripts will eat up to 50% of your CPU to render 1,000 particles. Sparticles will do the same while only using 9% and will run at a buttery 120fps if your device can refresh that fast!

Sparticles was built because other offerings in the space were either doing way too much and adding too many kb to load, or they were just too slow and unable to serve enough particles to lower end devices without chugging along jankily!

I used to get a lot of requests from Editorial/Content teams who wanted snow/sparkles/whatever on their home page during events, and I either had to reject because the plugins were killing our user's devices or accept and live knowing I've failed the users/customers! 😢 ~~ so Sparticles should fix that!

mobile

Please take care of your mobile users! They are probably your primary user if you're running a commercial or non-tech website! use a script like below to determine the amount of particles based on their device;

  let myElement = document.getElementById("myDiv");
  // PLEASE DON'T PUSH A TON OF ANIMATION ON MOBILES!
  let count = (/Mobi|Android/i.test(navigator.userAgent)) ? 100 : 500;
  let mySparticles = new Sparticles(myElement, { count: count }, 400);

why "Sparticles" ?

particles + [ speed ⚡ | snow ❄ | sparkles ✨ | stars ⭐ ] = Sparticles 🌈