Coder Social home page Coder Social logo

simeydotme / sparticles Goto Github PK

View Code? Open in Web Editor NEW
232.0 8.0 19.0 1.87 MB

JavaScript Particles in Canvas ~~ Fast, Lightweight, High Performance.

Home Page: https://sparticlesjs.dev

License: Mozilla Public License 2.0

JavaScript 89.27% HTML 6.05% CSS 3.27% Svelte 1.42%
particles canvas sparticles javascript animation effect effects particle particlesjs particles-js

sparticles's Introduction

Sparticles

javascript particles in canvas

Lightweight, High Performance Particles in Canvas.
For those occasions when you ๐Ÿ‘ just ๐Ÿ‘ gotta ๐Ÿ‘ have ๐Ÿ‘ sparkles, snow, or stars on your homepage!

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;
    (make sure this code runs after you've included the script above.)
<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.

parameter type default description
node HTMLElement document.body the element in the DOM which the Sparticles will append to
options Object {} an object with all the options for the instance
width Number node.clientWidth the width of the canvas element
height Number node.clientWidth the height of the canvas element (defaults to width)

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


  • Supply nothing and get a default Sparticle instance on the <body>
let mySparticles = new Sparticles();
  • Supply a single HTMLElement parameter for a default Sparticle instance on that element
let mySparticles = new Sparticles(document.getElementById("myDiv"));
  • Supply a single Object parameter to customise a Sparticle instance on the <body>
let mySparticles = new Sparticles({ color: "red" });
  • Supply the width and height parameters for a custom size
let mySparticles = new Sparticles({ color: "red" }, 400, 300);

options

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

option type default description
composition String source-over canvas globalCompositeOperation value for particles
count Number 50 number of particles on the canvas simultaneously
speed Number 10 default velocity of every particle
parallax Number 1 speed multiplier effect for larger particles (0 = none)
direction Number 180 default direction of particles in degrees (0 = โ†‘, 180 = โ†“)
xVariance Number 2 random deviation of particles on x-axis from default direction
yVariance Number 2 random deviation of particles on y-axis from default direction
rotate Boolean true can particles rotate
rotation Number 1 default rotational speed for every particle
alphaSpeed Number 10 rate of change in alpha over time
alphaVariance Number 1 random deviation of alpha change
minAlpha Number 0 minumum alpha value of every particle
maxAlpha Number 1 maximum alpha value of every particle
minSize Number 1 minimum size of every particle
maxSize Number 10 maximum size of every particle
bounce Boolean false should the particles bounce off edge of canvas
drift Number 1 the "driftiness" of particles which have a horizontal/vertical direction
glow Number 0 the glow effect size of each particle
twinkle Boolean false particles to exhibit an alternative alpha transition as "twinkling"
style String fill fill style of particles (one of; "fill", "stroke" or "both")
shape String/Array circle shape of particles (any of; circle, square, triangle, diamond, line, image) or "random"
color String/Array random css color as string, or array of color strings (can also be "random")
randomColor Function randomHsl() function for returning a random color when the color is set as "random"
randomColorCount Number 3 number of random colours when the color is set as "random"
imageUrl String/Array if 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

  • Type: Number
  • Default: 50
  • Range: 1 - 10000

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

speed

  • Type: Number
  • Default: 10
  • Range: 0 - 100

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

  • Type: Number
  • Default: 1
  • Range: 0 - 20

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

  • Type: Number
  • Default: 180
  • Range: 0 - 360

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

xVariance

  • Type: Number
  • Default: 2
  • Range: 0 - 20

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

  • Type: Number
  • Default: 2
  • Range: 0 - 20

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

  • Type: Boolean
  • Default: true

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

rotation

  • Type: Number
  • Default: 1
  • Range: 0 - 20

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

  • Type: Number
  • Default: 10
  • Range: 0 - 50

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

  • Type: Number
  • Default: 2
  • Range: 0 - 10

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

  • Type: Number
  • Default: 0
  • Range: -5 - +1

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

  • Type: Number
  • Default: 0
  • Range: 0 - +5

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

  • Type: Number
  • Default: 1
  • Range: 1 - 100

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

  • Type: Number
  • Default: 10
  • Range: 1 - 100

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

  • Type: String
  • Default: "fill"
  • Values: "fill", "stroke" or "both"

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

  • Type: Boolean
  • Default: false

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

  • Type: Number
  • Default: 1
  • Range: 1 - 20

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

  • Type: Number
  • Default: 0
  • Range: 0 - 50

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

twinkle

  • Type: Boolean
  • Default: false

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

color

  • Type: String / Array<String>
  • Default: "random"
  • Values: any valid css/html color string

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

  • Type: Function
  • Default: randomHSL()
  • Arguments: index, total

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

  • Type: Number
  • Default: 3
  • Range: 1 - 50

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

  • Type: String / Array<String>
  • Default: "circle"
  • Values: "circle", "square", "triangle", "line", "diamond", "star" or "image"

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

  • Type: String / Array<String>
  • Default: ""
  • Values: a valid url, or data-uri

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. This image should be a square (1:1)

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();
method description
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

  • โ„น It's quite easy to achieve 120fps+ with over 1,000 particles on a decent computer!

  • โš  But please remember your users are not all running super-computers with GPUs, they are probably on a mobile phone. Please avoid running heavy animations on phones! If you really have to then I'd advise reducing the particles down to 100 or less for a mobile device!

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 ๐ŸŒˆ

sparticles's People

Contributors

dependabot[bot] avatar simeydotme 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  avatar  avatar  avatar  avatar

sparticles's Issues

ReactJS Support

Hi, How to add this awesome library as a React component?

particles.js

import Sparticles from "sparticles";
import React, { useState, useEffect } from "react";

export default function Particles() {
  useEffect(() => {
    let mySparticles = new Sparticles({ color: "red", count: 10 }, 400, 300);
  });
  return <></>;
}

index.js

import Particles from "./particles";
export default function Nav() {

  return (
    <>
      <Particles />
      
    </>
  );
}

The particles did appear on my NextJS page but they always appear at the bottom.
How to make them appear in the Header.

Sparticles in absolute positione div

How I understand Sparticles can calculate width and height of target div has absolute position. I can setup width in pixels but I need widht 100%, height 100%

Weird issue with shape resolution

There's two issues with the resolution of the generated off-screen canvases for shapes.

  1. it appears the offscreen canvas is slightly too small to contain the whole shape causing little cut-off parts on the bottom/right side of the shape (fig1,fig2)

  2. it appears that when the "min" value is larger than the "max" value for shape-size, the image gets blurry (fig3)

fig1

Screen Shot 2021-07-26 at 3 02 54 PM

fig2

Screen Shot 2021-07-26 at 3 00 29 PM

fig3

Screen Shot 2021-07-26 at 3 00 52 PM

Image rendering bug or demo UX problem

Hi, cool little library! While playing with the demo at sparticlesjs.dev it took me a while to realise that when adding an image as the shape I had to add a color and then type "transparent" in place of the hex code in order to get the images to show. Removing all the colors didn't help. I'm not sure if this is a bug, or if it's just a UX thing that perhaps needs some work.

A couple of other smaller notes that I'll tack onto this issue because I'm not sure if they deserve their own:

  • It seems counter-intuitive that "image" is in the "shape" menu. I'd have thought that it would be part of the rendering of the shape. I.e. as an alternative to filling the shape with color, you can fill it with an image. That said, since images can have transparency, it does make sense that you'd want to be able to choose a color for the background, or specify that the background should be transparent.
  • It would be neat if you could (via the demo/config page) add multiple images (like you can do with colors), and ideally adjust the weightings of these images so that some images are more common than others. I know this is possible with the library, but the demo/config thing you've built is quite handy so I'd be nice to have that ability!
  • Edit: It looks like there's also a bug with the demo where the shape doesn't change when you try one of the presets. Here's a screen recording after opening an incognito window (since the demo seems to remember stuff via localStorage) and changing the preset to the galaxy.

Cheers!

Firefox drawImage() fails with an SVG image without width and height

In my project:

import image from "../assets/images/image.svg";
let options = {
	...
	shape: "image",
	imageUrl: image,
};

Particles are rendering great on safari and chrome, but on firefox the console is getting filled with these errors:
DOMException: CanvasRenderingContext2D.drawImage: Passed-in canvas is empty

drawimageerr@2x

After some debugging, my best guess is that it's related to this Firefox bug:
drawImage() fails silently when drawing an SVG image without @width or @height

My image.svg indeed does not have a width and a height set, which causes the particle canvas to have a size of 0 and fail to render.

If this can't be fixed it might be worth mentioning it on the readme or displaying a dedicated error in the console when the project is not in production.

Thanks for this project, it's easy to get up and running!

svelteKit [ERROR]: Two output files share the same path but have different contents

X [ERROR] Two output files share the same path but have different contents: node_modules\.vite\deps_temp_96733fdf\Sparticles.js   

6:15:59 PM [vite] error while updating dependencies:
Error: Build failed with 1 error:
error: Two output files share the same path but have different contents: node_modules\.vite\deps_temp_96733fdf\Sparticles.js      
    at failureErrorWithLog (D:\cloud\cloud\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:1636:15)
    at D:\cloud\cloud\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:1048:25
    at D:\cloud\cloud\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:1512:9
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)



Render issue

Hello, thank you for the library.

I've encountered a bug and I confess I don't really know how to explain the problem but I'll try to show it (it's my first issue).
The problem is simple when I want to make particles appear in the background of the "body" it works but it does not extend to the entire body and it does not appear on the last two sections of the "body". What I don't understand is that when I use "inspect element", it works as if it reloads the effect and applies it again.

Thanks in advance for the answer and sorry if I wasn't clear enough!

Pictures:
[Before
AVANT_1
AVANT_3
]

[After "nspect element"
APRES
]

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.